Javascript jQuery:查找具有特定自定义属性的元素

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

jQuery: Find the element with a particular custom attribute

javascriptjquery

提问by Chro

I just want to find the element with a particular value for a custom attribute.

我只想找到具有自定义属性特定值的元素。

E.g. I want to find a the divwhich has the attribute data-divNumber="6".

例如,我想找到div具有属性的 the data-divNumber="6"

var number = 6;
var myDiv = $('[data-divNumber = number]');

I tried using http://api.jquery.com/attribute-equals-selector/but what I've done doesn't work.

我尝试使用http://api.jquery.com/attribute-equals-selector/但我所做的不起作用。

There is precisely one element with that particular value for the attribute.

恰好有一个元素具有该属性的特定值。

回答by Ali Foroughi

var number = 6;
var myDiv = $('div[data-divNumber="' + number + '"]');

回答by jfriend00

You need to do some string addition to get the number into your selector and the value needs to be quoted.

您需要进行一些字符串添加才能将数字放入选择器中,并且需要引用该值。

var number = 6;
var myDiv = $('[data-divNumber="' + number + '"]');

What you're trying to produce after the string addition is this result:

添加字符串后您尝试生成的结果是:

$('[data-divNumber="6"]');

回答by legendofawesomeness

I think what you need is:

我认为你需要的是:

var number = 6;
var myDiv = $('[data-divNumber="'+number+'"]');

回答by Amuxix

With ES6 you can use string interpolation:

使用 ES6,您可以使用字符串插值:

let number = 6;
let myDiv = $(`div[data-divNumber="${number}"]`);