javascript 检查特定数据属性值的存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18519375/
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
Check for existence of specific data attribute value
提问by mheavers
I'm trying to select a DOM element with a specific attribute value. I'd like to avoid an each() loop, but all I've seen in jQuery is the ability to detect the existence of the data attribute, not its value. So, I want to accomplish something like this:
我正在尝试选择具有特定属性值的 DOM 元素。我想避免 each() 循环,但我在 jQuery 中看到的只是检测数据属性是否存在的能力,而不是它的值。所以,我想完成这样的事情:
if ($('.item[data-index="' + indexVal + '" ]'){
//if an .item with the data-index value of indexVal exists...
}
采纳答案by sd1sd1
try this:
试试这个:
if ($('.item[data-index="' + indexVal + '" ]').length > 0){
}
回答by Moazzam Khan
missing )
and $(selector)
should not be put in a if condition. it is always true
even it does not select anything.
丢失)
,$(selector)
不应置于 if 条件中。它总是true
即使它不选择任何东西。
if ($('.item[data-index="' + indexVal + '" ]').length) {
回答by Raphael Ribeiro
$('.item[data-index]').length > 0
$('.item[data-index]').length > 0
if you searching for specific value, you can insert the value in "" :
如果您搜索特定值,您可以在 "" 中插入值:
$('.item[data-index="123"]').length > 0
$('.item[data-index="123"]').length > 0
or
或者
$('.item[data-index]').is('*')
$('.item[data-index]').is('*')
回答by Micha? Sza?apski
should be
应该
if ($('.item[data-index="' + indexVal + '" ]')){
//if an .item with the data-index value of indexVal exists...
}
or
或者
if(jQuery('.item').attr('data-index') == indexVal){
}