[jquery] jQuery는 데이터 속성 값을 기반으로 요소를 찾는 방법?

다음과 같은 시나리오가 있습니다.

var el = 'li';

<li>페이지에 각각 5 개의 data-slide=number속성 이있는 숫자가 있습니다 (각각 1,2,3,4,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 + "']"); 


답변

모든 것을 입력하지 않으려는 경우 data 속성으로 쿼리하는 더 짧은 방법이 있습니다.

$("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


답변

나는에 개선 싸이코 BRM의 filterByData 확장 jQuery를합니다.

이전 확장이 키-값 쌍을 검색 한 경우이 확장을 사용하면 값에 관계없이 데이터 속성이 있는지 검색 할 수 있습니다.

(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

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


답변

JQuery없이 ES6

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

JQuery에 대한 질문은 알고 있지만 독자는 순수한 JS 메소드를 원할 수 있습니다.


답변

jQuery와 data- * 속성을 사용하여 요소를 가져 오는 동안 동일한 문제에 직면했습니다.

참고로 가장 짧은 코드는 다음과 같습니다.

이것은 내 HTML 코드입니다.

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

이것은 내 jQuery 선택기입니다.

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


답변

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

이것이 더 잘 작동하기를 바랍니다.

감사