jQuery 通过数据属性选择元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2487747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:36:44  来源:igfitidea点击:

Selecting element by data attribute

jqueryhtmlcustom-data-attribute

提问by Hazem Salama

Is there an easy and straight-forward method to select elements based on their dataattribute? For example, select all anchors that has data attribute named customerIDwhich has value of 22.

是否有一种简单直接的方法可以根据元素的data属性来选择元素?例如,选择所有名为 data 属性customerID值为 的锚点22

I am kind of hesitant to use relor other attributes to store such information, but I find it much harder to select an element based on what data is stored in it.

我有点犹豫是否使用rel或其他属性来存储此类信息,但我发现根据存储在其中的数据来选择元素要困难得多。

回答by Mathias Bynens

$('*[data-customerID="22"]');

You should be able to omit the *, but if I recall correctly, depending on which jQuery version you're using, this might give faulty results.

您应该可以省略*,但是如果我没记错的话,根据您使用的 jQuery 版本,这可能会产生错误的结果。

Note that for compatibility with the Selectors API (document.querySelector{,all}), the quotes around the attribute value (22) may not be omitted in this case.

请注意,为了与 Selectors API ( document.querySelector{,all})兼容,在这种情况下不能省略属性值 ( 22)周围的引号。

Also, if you work with data attributes a lot in your jQuery scripts, you might want to consider using the HTML5 custom data attributes plugin. This allows you to write even more readable code by using .dataAttr('foo'), and results in a smaller file size after minification (compared to using .attr('data-foo')).

此外,如果您在 jQuery 脚本中经常使用数据属性,则可能需要考虑使用HTML5 自定义数据属性插件。这使您可以使用 编写更具可读性的代码.dataAttr('foo'),并在缩小后生成更小的文件大小(与使用 相比.attr('data-foo'))。

回答by JTG

For people Googling and want more general rules about selecting with data-attributes:

对于使用谷歌搜索并想要更多关于使用数据属性进行选择的一般规则的人:

$("[data-test]")will select any element that merely hasthe data attribute (no matter the value of the attribute). Including:

$("[data-test]")将选择任何仅具有data 属性的元素(无论该属性的值如何)。包含:

<div data-test=value>attributes with values</div>
<div data-test>attributes without values</div>


$('[data-test~="foo"]')will select any element where the data attribute containsfoobut doesn't have to be exact, such as:

$('[data-test~="foo"]')将选择 data 属性包含foo但不必精确的任何元素,例如:

<div data-test="foo">Exact Matches</div>
<div data-test="this has the word foo">Where the Attribute merely contains "foo"</div>


$('[data-test="the_exact_value"]')will select any element where the data attribute exact value is the_exact_value, for example:

$('[data-test="the_exact_value"]')将选择数据属性精确值为 的任何元素the_exact_value,例如:

<div data-test="the_exact_value">Exact Matches</div>

but not

但不是

<div data-test="the_exact_value foo">This won't match</div>

回答by drzaus

Using $('[data-whatever="myvalue"]')will select anything with html attributes, but in newer jQueries it seems that if you use $(...).data(...)to attach data, it uses some magic browser thingy and does not affect the html, therefore is not discovered by .findas indicated in the previous answer.

Using$('[data-whatever="myvalue"]')将选择具有 html 属性的任何内容,但在较新的 jQueries 中,似乎如果您用于$(...).data(...)附加数据,它会使用一些神奇的浏览器并且不会影响 html,因此不会.find如上一个答案中所示被发现。

Verify (tested with 1.7.2+) (also see fiddle): (updated to be more complete)

验证(使用 1.7.2+ 测试)(另请参阅fiddle):( 更新为更完整)

var $container = $('<div><div id="item1"/><div id="item2"/></div>');

// add html attribute
var $item1 = $('#item1').attr('data-generated', true);

// add as data
var $item2 = $('#item2').data('generated', true);

// create item, add data attribute via jquery
var $item3 = $('<div />', {id: 'item3', data: { generated: 'true' }, text: 'Item 3' });
$container.append($item3);

// create item, "manually" add data attribute
var $item4 = $('<div id="item4" data-generated="true">Item 4</div>');
$container.append($item4);

// only returns $item1 and $item4
var $result = $container.find('[data-generated="true"]');

回答by Sjoerd Pottuit

I haven't seen a JavaScript answer without jQuery. Hopefully it helps someone.

我还没有看到没有 jQuery 的 JavaScript 答案。希望它可以帮助某人。

var elements = document.querySelectorAll('[data-customerID="22"]');

elements[0].innerHTML = 'it worked!';
<a data-customerID='22'>test</a>

Info:

信息:

回答by Travis J

To select all anchors with the data attribute data-customerID==22, you should include the ato limit the scope of the search to only that element type. Doing data attribute searches in a large loop or at high frequency when there are many elements on the page can cause performance issues.

要选择具有 data 属性的所有锚点data-customerID==22,您应该包含a以将搜索范围限制为仅该元素类型。当页面上有很多元素时,以大循环或高频率进行数据属性搜索会导致性能问题。

$('a[data-customerID="22"]');

回答by etoxin

Native JS Examples

原生 JS 示例

Get NodeList of elements

获取元素的节点列表

var elem = document.querySelectorAll('[data-id="container"]')

html: <div data-id="container"></div>

html: <div data-id="container"></div>

Get the first element

获取第一个元素

var firstElem = document.querySelector('[id="container"]')

html: <div id="container"></div>

html: <div id="container"></div>

Target a collection of nodes which returns a nodelist

以返回节点列表的节点集合为目标

document.getElementById('footer').querySelectorAll('[data-id]')

html:

html:

<div class="footer">
    <div data-id="12"></div>
    <div data-id="22"></div>
</div>

Get elements based on multiple (OR) data values

根据多个 (OR) 数据值获取元素

document.querySelectorAll('[data-section="12"],[data-selection="20"]')

html:

html:

<div data-selection="20"></div>
<div data-section="12"></div>

Get elements based on combined (AND) data values

根据组合 (AND) 数据值获取元素

document.querySelectorAll('[data-prop1="12"][data-prop2="20"]')

html:

html:

<div data-prop1="12" data-prop2="20"></div>

Get items where the value starts with

获取值开头的项目

document.querySelectorAll('[href^="https://"]')

回答by Anton Danilchenko

The construction like this: $('[data-XXX=111]')isn't working in Safari 8.0.

这样的结构:$('[data-XXX=111]')Safari 8.0 中不起作用。

If you set data attribute this way: $('div').data('XXX', 111), it only works if you set data attribute directly in DOM like this: $('div').attr('data-XXX', 111).

如果您以这种方式设置 data 属性:$('div').data('XXX', 111),则仅当您像这样直接在 DOM 中设置 data 属性时才有效:$('div').attr('data-XXX', 111)

I think it's because jQuery team optimized garbage collector to prevent memory leaks and heavy operations on DOM rebuilding on each change data attribute.

我认为这是因为 jQuery 团队优化了垃圾收集器,以防止内存泄漏和对每个更改数据属性的 DOM 重建的繁重操作。

回答by Razan Paul

via Jquery filter() method:

通过 Jquery filter() 方法:

http://jsfiddle.net/9n4e1agn/1/

http://jsfiddle.net/9n4e1agn/1/

HTML:

HTML:

<button   data-id='1'>One</button>
<button   data-id='2'>Two</button>

JavaScript:

JavaScript:

$(function() {    
    $('button').filter(function(){
        return $(this).data("id")   == 2}).css({background:'red'});  
     });

回答by user55318

For this to work in Chrome the value must nothave another pair of quotes.

为了在 Chrome 中工作,该值不能有另一对引号。

It only works, for example, like this:

例如,它只能像这样工作:

$('a[data-customerID=22]');

回答by XDS

It's sometimes desirable to filter elements based on whether they have data-items attached to them programmatically(aka not via dom-attributes):

有时需要根据元素是否以编程方式(也不是通过 dom-attributes)附加数据项来过滤元素:

$el.filter(function(i, x) { return $(x).data('foo-bar'); }).doSomething();

The above works but is not very readable. A better approach is to use a pseudo-selector for testing this sort of thing:

以上工作,但不是很可读。更好的方法是使用伪选择器来测试这类事情:

$.expr[":"].hasData = $.expr.createPseudo(function (arg) {
    return function (domEl) {
        var $el = $(domEl);
        return $el.is("[" + ((arg.startsWith("data-") ? "" : "data-") + arg) + "]") || typeof ($el.data(arg)) !== "undefined";
    };
});

Now we can refactor the original statement to something more fluent and readable:

现在我们可以将原始语句重构为更流畅和可读的内容:

$el.filter(":hasData('foo-bar')").doSomething();