Programing

식별자 (id)에 대한 와일드 카드 선택기가 있습니까?

lottogame 2020. 11. 19. 07:47
반응형

식별자 (id)에 대한 와일드 카드 선택기가 있습니까?


특정 이름 지정 체계를 공유하는 알 수없는 양의 식별자가있는 경우 jQuery를 사용하여 한 번에 모두 가져 오는 방법이 있습니까?

// These are the IDs I'd like to select
#instance1
#instance2
#instance3
#instance4

// What do I need to add or how do I need to modify this jQuery selector in order to select all the IDs above?
("#instanceWILDCARD").click(function(){}

속성은 시작-와 선택 ( '^=) 과 같이, 사용자의 ID에 대해 작동합니다 :

$("[id^=instance]").click(function() {
  //do stuff
});

그러나 요소에 공통 클래스를 제공하는 것을 고려하십시오 (예 : (I crack yourself up)) .instance해당 선택기를 사용하십시오.

$(".instance").click(function() {
  //do stuff
});

ID가 아닌 클래스를 실제로 일치 시키려면 클래스가 여러 값을 가질 수 있으므로 구문이 조금 더 복잡합니다.

// handle elements like <div class="someclass1"></div>
$('[class^="someclass"]').click(function() {
   // do stuff
});

// handle elements like <div class="foo someclass1"></div>
$('[class*=" someclass"]').click(function() {
   // do stuff
});

아무도 (jQuery의 선택기 기능을 확장하여) 자신 만의 필터 선택기를 만드는 것에 대해 언급하지 않았다는 것에 놀랐습니다. 여기에서는 와일드 카드 문자열을 받아들이고 일치하는 모든 요소를 ​​찾는 "likeClass"및 "likeId"라는 와일드 카드 선택기를 만들었습니다 (정규식 일치와 유사).

암호:

$.expr[':'].likeClass = function(match){
      return $('[class*=" '+ match +'"]');
};
$.expr[':'].likeId = function(match){
      return $('[id*=" '+ match +'"]');
};

사용 예 :

이제 .content-1, .content-2, .content-n ... 등과 같은 유사한 이름을 가진 여러 div 요소가 있고이를 선택하려고한다고 가정 해 보겠습니다. 이제 케이크입니다!

$ ( 'div : likeClass (content-)'); // 비슷한 클래스 이름을 가진 모든 요소를 ​​반환합니다. content- *

또는

$ ( 'div : likeClass (content-)'); // ID가 유사한 모든 요소를 ​​반환합니다. content- *

네, 한 가지 더 ... 당신도 연결할 수 있습니다. :)

$('li:likeId(slider-content-)').hide().addClass('sliderBlock').first().fadeIn('fast');

즐겨!


jQuery가 있으면 추가 expr이나 멋진 것이 필요하지 않습니다.

jQuery('[class*="someclass"]').click(function(){
});

jQuery('[id*="someclass"]').click(function(){
});

언급 한대로 : https://stackoverflow.com/a/2220874/2845401


class = "instance"그들 모두에 할당 하고 사용하여 선택하지 $('.instance')않습니까?


이들은 ID이지만 다음과 유사한 작업을 수행 할 수 있습니다.

$("[id^='instance']").click(...)

하지만 비용이 많이 듭니다. a) 요소 유형 또는 b) DOM에서 다음과 같은 일반적인 위치를 지정할 수 있으면 도움이됩니다.

$("#someContentDiv span[id^='instance']").click(...)

[id^='...']선택기는 기본적으로 유사한 그 ID 시작이 문자열 요소 발견 "를 의미한다 id$=(이 문자열 ID 단부) 등

여기 jQuery 문서 페이지 에서 포괄적 인 목록을 찾을 수 있습니다 .


Use the carrot.

$("div[id^=instance]").hide();

jsFiddle example


We can do it this way:

$(document).ready(function () {
    $('[id*=btnOk]').live("click", function () {

    });
});

This is the only correct answer to the id wildcard question.

$('[id*="Wild card in double quotes"]') 

This will get "Wild card in double quotes. And there's more!!!", and also "More BS in front of Wild. Wild card in double quotes".

You should use quote marks that are different than your '[]' tags.

참고URL : https://stackoverflow.com/questions/3697542/is-there-a-wildcard-selector-for-identifiers-id

반응형