最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check for existence of specific data attribute value - Stack Overflow

programmeradmin8浏览0评论

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 acplish something like this:

if ($('.item[data-index="' + indexVal + '" ]'){
  //if an .item with the data-index value of indexVal exists...
}

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 acplish something like this:

if ($('.item[data-index="' + indexVal + '" ]'){
  //if an .item with the data-index value of indexVal exists...
}
Share Improve this question edited Nov 17, 2015 at 15:36 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Aug 29, 2013 at 19:20 mheaversmheavers 30.2k62 gold badges198 silver badges326 bronze badges 1
  • appending [0] will Boolean the jQuery hits, just like .length>0 or just .length if in an if() statment... – dandavis Commented Aug 29, 2013 at 19:43
Add a ment  | 

4 Answers 4

Reset to default 8

missing ) and $(selector) should not be put in a if condition. it is always true even it does not select anything.

if ($('.item[data-index="' + indexVal + '" ]').length) {

try this:

if ($('.item[data-index="' + indexVal + '" ]').length > 0){

}

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){
}

$('.item[data-index]').length > 0

if you searching for specific value, you can insert the value in "" :

$('.item[data-index="123"]').length > 0

or

$('.item[data-index]').is('*')

发布评论

评论列表(0)

  1. 暂无评论