检查是否存在特定数据属性值

时间:2013-08-29 19:20:23

标签: javascript jquery

我正在尝试选择具有特定属性值的DOM元素。我想避免使用each()循环,但我在jQuery中看到的只是能够检测数据属性的存在,而不是它的值。所以,我想完成这样的事情:

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

4 个答案:

答案 0 :(得分:7)

缺少)$(selector)不应该置于if条件中。它总是true,即使它没有选择任何东西。

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

答案 1 :(得分:4)

试试这个:

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

}

答案 2 :(得分:0)

应该是

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

if(jQuery('.item').attr('data-index') == indexVal){
}

答案 3 :(得分:0)

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

如果您要搜索特定值,可以将值插入“”:

$('。item [data-index =“ 123”]')。length> 0

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