Programing

개별 클래스 이름에 'starts with'선택기를 사용

lottogame 2020. 6. 19. 19:25
반응형

개별 클래스 이름에 'starts with'선택기를 사용


내가 다음을 가지고 있다면 :

<div class="apple-monkey"></div>
<div class="apple-horse"></div>
<div class="cow-apple-brick"></div>

다음 선택기를 사용하여 처음 두 DIV를 찾을 수 있습니다.

$("div[class^='apple-']")

그러나 내가 이것을 가지고 있다면 :

<div class="some-other-class apple-monkey"></div>
<div class="apple-horse"></div>
<div class="cow-apple-brick"></div>

첫 번째 div의 클래스가 문자열로 반환되고 실제로 'apple-'로 시작하지 않고 'some-'으로 시작하기 때문에 두 번째 DIV 만 찾을 것입니다.

그 주위의 한 가지 방법은 시작을 사용하지 않고 대신 다음을 포함하는 것입니다.

$("div[class*='apple-']")

그 문제는 내 예제에서 3 차 DIV도 선택한다는 것입니다.

질문 : jQuery를 통해 전체 클래스 속성이 아닌 개별 클래스 이름에서 술어 선택기를 사용하는 올바른 방법은 무엇입니까? 클래스를 잡고 배열로 분할 한 다음 정규 표현식을 사용하여 각 개별 클래스를 반복하는 것이 문제입니까? 아니면 더 우아하고 덜 장황한 솔루션이 있습니까?


"apple-"로 시작하는 클래스와 "apple-"을 포함하는 클래스

$("div[class^='apple-'],div[class*=' apple-']")

"애플"을 자체 클래스로 만드는 것이 좋습니다. 사용을 선택할 div.apple수있는 것이 훨씬 빠르기 때문에 시작 / 종료를 피해야합니다 . 더 우아한 솔루션입니다. 작업을 더 간단하고 빠르게 만들면 사물을 별도의 클래스로 나누는 것을 두려워하지 마십시오.


이것은 접두사입니다

$("div[class^='apple-']")

이것은 시작하기위한 것이므로 거기에 '-'문자가 필요하지 않습니다.

$("div[class|='apple']")

https://api.jquery.com/category/selectors/ 에서 jQuery 선택기의 다른 멋진 변형을 찾을 수 있습니다.


여기에 가장 좋은 대답은 asker의 특정 사례에 대한 해결 방법이지만 실제로 개별 클래스 이름에 'starts with'를 사용하는 솔루션을 찾고 있다면 다음을 수행하십시오.

:acp()"클래스 접두사"라는 이 사용자 정의 jQuery 선택기를 사용할 수 있습니다 . 코드는이 게시물의 맨 아래에 있습니다.

var test = $('div:acp("starting_text")');

<div>클래스의 시작 위치에 있는지 또는 클래스 속성 문자열의 다른 위치에 관계없이 주어진 문자열로 시작하는 클래스 이름이 하나 이상 (이 예에서는 "starting_text") 인 모든 요소를 선택합니다 .

<div id="1" class="apple orange lemon" />
<div id="2" class="orange applelemon banana" />
<div id="3" class="orange lemon apple" />
<div id="4" class="lemon orangeapple" />
<div id="5" class="lemon orange" />

var startsWithapp = $('div:acp("app")');

이것은 요소 1, 2 및 3을 반환하지만 4 또는 5 는 반환 하지 않습니다 .

다음 :acp은 어디에나 넣을 수 있는 커스텀 셀렉터 의 선언입니다 .

$(function(){
    $.expr[":"].acp = function(elem, index, m){
          var regString = '\\b' + m[3];
          var reg = new RegExp(regString, "g");
          return elem.className.match(reg);
    }
});

백엔드 제어가없는 웹 사이트에서 GreaseMonkey 해킹을 많이 수행하기 때문에이 작업을 수행 했으므로 동적 접미사가있는 클래스 이름을 가진 요소를 자주 찾아야합니다. 매우 유용했습니다.


이 시도:

$("div[class]").filter(function() {
    var classNames = this.className.split(/\s+/);
    for (var i=0; i<classNames.length; ++i) {
        if (classNames[i].substr(0, 6) === "apple-") {
            return true;
        }
    }
    return false;
})

<div class="apple-monkey"></div>
<div class="apple-horse"></div>
<div class="cow-apple-brick"></div>

in this case as question Josh Stodola answer is correct Classes that start with "apple-" plus classes that contain " apple-"

$("div[class^='apple-'],div[class*=' apple-']")

but if element have multiple classes like this

<div class="some-class apple-monkey"></div>
<div class="some-class apple-horse"></div>
<div class="some-class cow-apple-brick"></div>

then Josh Stodola's solution will do not work
for this have to do some thing like this

$('.some-parent-class div').filter(function () {
  return this.className.match(/\bapple-/);// this is for start with
  //return this.className.match(/apple-/g);// this is for contain selector
}).css("color","red");

may be it helps some one else thanks

참고URL : https://stackoverflow.com/questions/2178416/using-starts-with-selector-on-individual-class-names

반응형