簡體   English   中英

jQuery 如何根據數據屬性值查找元素?

[英]jQuery how to find an element based on a data-attribute value?

我有以下場景:

var el = 'li';

頁面上有 5 個<li> ,每個都有一個data-slide=number屬性(數字分別為 1,2,3,4,5)

我現在需要找到映射到var current = $('ul').data(current);的當前活動幻燈片編號var current = $('ul').data(current); 並在每次幻燈片更改時更新。

到目前為止,我的嘗試沒有成功,嘗試構建與當前幻燈片匹配的選擇器:

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

不匹配/返回任何東西......

我不能對li部分進行硬編碼的原因是,這是一個用戶可訪問的變量,如果需要,可以更改為不同的元素,因此它可能並不總是li

關於我缺少什么的任何想法?

您必須將current的值注入到Attribute Equals選擇器中:

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

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

我知道問題是關於 JQuery 的,但讀者可能想要一個純 JS 方法。

我改進了psycho brm對jQuery的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/

我在使用 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 [data-slide='" + current +"']"); 將適用於以下結構:

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

而這$("ul[data-slide='" + current +"']"); 將適用於:

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

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

我希望這可能會更好

謝謝

回到他最初的問題,關於如何在事先不知道元素類型的情況下進行這項工作,以下是這樣做的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM