使用 jQuery,如何通过多个数据属性选择元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18329943/
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
Using jQuery, how can I select elements by multiple data-attributes?
提问by Aaron
Consider this array of p
tags indexed by data attributes.
考虑这个p
由数据属性索引的标签数组。
<p class='my-class' data-id='0' data-id-index='1'></p>
<p class='my-class' data-id='0' data-id-index='2'></p>
<p class='my-class' data-id='1' data-id-index='1'></p>
<p class='my-class' data-id='1' data-id-index='2'></p>
To select a p
by data-id
and append text I can use:
要选择p
bydata-id
并附加文本,我可以使用:
$('.my-class[data-id="' + dataId + '"]').append(myText);
The above will append myText
to all p
tags with the same data-id
. But what about if I wanted to select by both data-id
and data-id-index
?
以上内容将附加myText
到所有p
具有相同data-id
. 但是如果我想同时选择data-id
和data-id-index
呢?
回答by SmokeyPHP
Do the same as you already did... the attribute selectors can be chained:
和你已经做的一样......属性选择器可以链接:
$('.my-class[data-id="' + dataId + '"][data-id-index="'+dataIdIndex+'"]').append(myText);