使用 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

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

Using jQuery, how can I select elements by multiple data-attributes?

jquery

提问by Aaron

Consider this array of ptags 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 pby data-idand append text I can use:

要选择pbydata-id并附加文本,我可以使用:

$('.my-class[data-id="' + dataId + '"]').append(myText);

The above will append myTextto all ptags with the same data-id. But what about if I wanted to select by both data-idand data-id-index?

以上内容将附加myText到所有p具有相同data-id. 但是如果我想同时选择data-iddata-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);