developer tip

id에 대한 jquery 선택기가 특정 텍스트로 시작됨

optionbox 2020. 8. 20. 08:13
반응형

id에 대한 jquery 선택기가 특정 텍스트로 시작됨


이 질문에 이미 답변이 있습니다.

이 jQuery 코드가 있습니다.

$( "#editDialog" ).dialog({
  autoOpen: false,
  show: {
    effect: "blind",
    duration: 1000
  },
  hide: {
    effect: "explode",
    duration: 1000
  }
});

하지만 다음과 같은 id를 가진 여러 div가 있습니다. editDialog-0, editDialog-1, ...., editDialog-n.

위의 모든 div에 대한 jQuery 코드를 어떻게 만들 수 있습니까?


속성 선택기로 시작하는 jquery 사용

$('[id^=editDialog]')

대체 솔루션-1 (적극 권장)

더 깨끗한 솔루션은 각 div 및 사용에 공통 클래스를 추가하는 것입니다.

$('.commonClass').

그러나 html 마크 업이 손에없고 어떤 이유로 든 변경할 수없는 경우 첫 번째 마크 업을 사용할 수 있습니다.

대체 솔루션-2 (인 경우 권장되지 않음 n is a large number) (@ Mihai Stancu의 제안에 따라)

$('#editDialog-0, #editDialog-1, #editDialog-2,...,#editDialog-n')

참고 : 선택기가 2 개 또는 3 개이고 목록이 변경되지 않으면 실행 가능한 솔루션 일 수 있지만 마을에 새 ID가있을 때 선택기를 업데이트해야하므로 확장 할 수 없습니다.


아직 언급하지 않았지만 유용하다고 생각되는 사항을 고려하여보다 광범위한 답변을 제공하겠습니다.

현재 문제에 대한 대답은

$("div[id^='editDialog']");

캐럿 (^)은 정규 표현식과 의미에서 가져옵니다 starts with.

해결책 1

// Select elems where 'attribute' ends with 'Dialog'
$("[attribute$='Dialog']"); 

// Selects all divs where attribute is NOT equal to value    
$("div[attribute!='value']"); 

// Select all elements that have an attribute whose value is like
$("[attribute*='value']"); 

// Select all elements that have an attribute whose value has the word foobar
$("[attribute~='foobar']"); 

// Select all elements that have an attribute whose value starts with 'foo' and ends
//  with 'bar'
$("[attribute^='foo'][attribute$='bar']");

attribute코드에서 상기와 같은 요소가 가질 수있는 임의 특성으로 변경 될 수있다 href, name, id또는 src.

해결 방법 2

수업 사용

// Matches all items that have the class 'classname'
$(".className");

// Matches all divs that have the class 'classname'
$("div.className");

해결책 3

나열하십시오 (이전 답변에도 언급 됨)

$("#id1,#id2,#id3");

해결 방법 4

개선 할 때 정규 표현식 (실제로 사용한 적이 없음, 솔루션 1 은 항상 충분했지만 결코 알 수 없습니다!

// Matches all elements whose id takes the form editDialog-{one_or_more_integers}
$('div').filter(function () {this.id.match(/editDialog\-\d+/)});

Add a common class to all the div. For example add foo to all the divs.

$('.foo').each(function () {
   $(this).dialog({
    autoOpen: false,
    show: {
      effect: "blind",
      duration: 1000
    },
    hide: {
      effect: "explode",
      duration: 1000
    }
  });
});

If all your divs start with editDialog as you stated, then you can use the following selector:

$("div[id^='editDialog']")

Or you could use a class selector instead if it's easier for you

<div id="editDialog-0" class="editDialog">...</div>

$(".editDialog")

참고URL : https://stackoverflow.com/questions/23223526/jquery-selector-for-id-starts-with-specific-text

반응형