program tip

jQuery 데이터 속성 값을 기반으로 요소를 찾는 방법은 무엇입니까?

radiobox 2020. 9. 28. 08:50
반응형

jQuery 데이터 속성 값을 기반으로 요소를 찾는 방법은 무엇입니까?


다음 시나리오가 있습니다.

var el = 'li';

<li>페이지에는 각각 data-slide=number속성 (숫자는 각각 1,2,3,4,5 임) 이있는 5 개가 있습니다 .

이제 var current = $('ul').data(current);각 슬라이드 변경에 매핑되고 업데이트 되는 현재 활성 슬라이드 번호를 찾아야합니다 .

지금까지는 현재 슬라이드와 일치하는 선택기를 구성하려고 시도했지만 실패했습니다.

$('ul').find(el+[data-slide=+current+]);

일치하지 않거나 아무것도 반환하지 않습니다…

li부분을 하드 코딩 할 수없는 이유 는 필요한 경우 다른 요소로 변경할 수있는 사용자 액세스 가능 변수이기 때문에 항상 li.

내가 놓친 것에 대한 아이디어가 있습니까?


당신의 가치 주입해야 current특성이 같음 선택기를 :

$("ul").find(`[data-slide='${current}']`)

이전 JavaScript 환경 (ES5 이하)의 경우 :

$("ul").find("[data-slide='" + current + "']"); 

모두 입력하고 싶지 않은 경우 데이터 속성으로 쿼리하는 더 짧은 방법이 있습니다.

$("ul[data-slide='" + current +"']");

참고 : http://james.padolsey.com/javascript/a-better-data-selector-for-jquery/


[data-x = ...]로 검색 할 때 jQuery.data (..) setter에서는 작동하지 않습니다 .

$('<b data-x="1">'  ).is('[data-x=1]') // this works
> true

$('<b>').data('x', 1).is('[data-x=1]') // this doesn't
> false

$('<b>').attr('data-x', 1).is('[data-x=1]') // this is the workaround
> true

대신 이것을 사용할 수 있습니다.

$.fn.filterByData = function(prop, val) {
    return this.filter(
        function() { return $(this).data(prop)==val; }
    );
}

$('<b>').data('x', 1).filterByData('x', 1).length
> 1

jQuery 에 대한 psycho brm의 filterByData 확장개선했습니다 .

이전 확장이 키-값 쌍을 검색 한 경우이 확장을 사용하면 값에 관계없이 데이터 속성의 존재를 추가로 검색 할 수 있습니다.

(function ($) {

    $.fn.filterByData = function (prop, val) {
        var $self = this;
        if (typeof val === 'undefined') {
            return $self.filter(
                function () { return typeof $(this).data(prop) !== 'undefined'; }
            );
        }
        return $self.filter(
            function () { return $(this).data(prop) == val; }
        );
    };

})(window.jQuery);

용법:

$('<b>').data('x', 1).filterByData('x', 1).length    // output: 1
$('<b>').data('x', 1).filterByData('x').length       // output: 1

// test data
function extractData() {
  log('data-prop=val ...... ' + $('div').filterByData('prop', 'val').length);
  log('data-prop .......... ' + $('div').filterByData('prop').length);
  log('data-random ........ ' + $('div').filterByData('random').length);
  log('data-test .......... ' + $('div').filterByData('test').length);
  log('data-test=anyval ... ' + $('div').filterByData('test', 'anyval').length);
}

$(document).ready(function() {
  $('#b5').data('test', 'anyval');
});

// the actual extension
(function($) {

  $.fn.filterByData = function(prop, val) {
    var $self = this;
    if (typeof val === 'undefined') {
      return $self.filter(

        function() {
          return typeof $(this).data(prop) !== 'undefined';
        });
    }
    return $self.filter(

      function() {
        return $(this).data(prop) == val;
      });
  };

})(window.jQuery);


//just to quickly log
function log(txt) {
  if (window.console && console.log) {
    console.log(txt);
    //} else {
    //  alert('You need a console to check the results');
  }
  $("#result").append(txt + "<br />");
}
#bPratik {
  font-family: monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="bPratik">
  <h2>Setup</h2>
  <div id="b1" data-prop="val">Data added inline :: data-prop="val"</div>
  <div id="b2" data-prop="val">Data added inline :: data-prop="val"</div>
  <div id="b3" data-prop="diffval">Data added inline :: data-prop="diffval"</div>
  <div id="b4" data-test="val">Data added inline :: data-test="val"</div>
  <div id="b5">Data will be added via jQuery</div>
  <h2>Output</h2>
  <div id="result"></div>

  <hr />
  <button onclick="extractData()">Reveal</button>
</div>

또는 바이올린 : http://jsfiddle.net/PTqmE/46/


I have faced the same issue while fetching elements using jQuery and data-* attribute.

so for your reference the shortest code is here:

This is my HTML Code:

<section data-js="carousel"></section>
<section></section>
<section></section>
<section data-js="carousel"></section>

This is my jQuery selector:

$('section[data-js="carousel"]');
// this will return array of the section elements which has data-js="carousel" attribute.

Without JQuery, ES6

document.querySelectorAll(`[data-slide='${current}']`);

I know the question is about JQuery, but readers may want a pure JS method.


$("ul").find("li[data-slide='" + current + "']");

I hope this may work better

thanks


This selector $("ul [data-slide='" + current +"']"); will work for following structure:

<ul><li data-slide="item"></li></ul>  

While this $("ul[data-slide='" + current +"']"); will work for:

<ul data-slide="item"><li></li></ul>


Going back to his original question, about how to make this work without knowing the element type in advance, the following does this:

$(ContainerNode).find(el.nodeName + "[data-slide='" + current + "']");

참고URL : https://stackoverflow.com/questions/4191386/jquery-how-to-find-an-element-based-on-a-data-attribute-value

반응형