jQuery jQuery按数据属性值查找元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21756777/
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-27 01:40:52  来源:igfitidea点击:

jQuery find element by data attribute value

jqueryhtmlcsscustom-data-attribute

提问by MrUpsidown

I have a few elements like below:

我有几个元素,如下所示:

<a class="slide-link" href="#" data-slide="0">1</a>
<a class="slide-link" href="#" data-slide="1">2</a>
<a class="slide-link" href="#" data-slide="2">3</a>

How can I add a class to the element which has a data-slideattribute value of 0(zero)?

如何向data-slide属性值为0(零)的元素添加类?

I have tried many different solutions but nothing worked. An example:

我尝试了许多不同的解决方案,但没有任何效果。一个例子:

$('.slide-link').find('[data-slide="0"]').addClass('active');

Any idea?

任何的想法?

回答by Tushar Gupta - curioustushar

Use Attribute Equals Selector

使用属性等于选择器

$('.slide-link[data-slide="0"]').addClass('active');

Fiddle Demo

Fiddle Demo

.find()

。找()

it works down the tree

它在树下工作

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

获取当前匹配元素集中每个元素的后代,由选择器、jQuery 对象或元素过滤。

回答by Anton

You can also use .filter()

你也可以使用.filter()

$('.slide-link').filter('[data-slide="0"]').addClass('active');

回答by Aleshanee

I searched for a the same solution with a variable instead of the String.
I hope i can help someone with my solution :)

我用变量而不是字符串搜索了相同的解决方案。
我希望我能帮助别人解决我的问题:)

var numb = "3";
$(`#myid[data-tab-id=${numb}]`);

回答by Girish

you can also use andSelf()method to get wrapper DOM contain then find()can be work around as your idea

您还可以使用andSelf()方法来获取包装器 DOM 包含然后find()可以解决您的想法

$(function() {
  $('.slide-link').andSelf().find('[data-slide="0"]').addClass('active');
})
.active {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class="slide-link" href="#" data-slide="0">1</a>
<a class="slide-link" href="#" data-slide="1">2</a>
<a class="slide-link" href="#" data-slide="2">3</a>