2013-08-29 3 views
5

특정 속성 값을 가진 DOM 요소를 선택하려고합니다. each() 루프는 피하고 싶지만 jQuery에서 본 모든 것은 데이터 속성의 존재 여부를 감지하는 것이지 값은 아닙니다. 그래서, 이런 식으로 뭔가를 달성하고 싶다 : )$(selector) 누락특정 데이터 속성 값의 존재 여부 확인

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

[0] jQuery를 그냥 .length 같은 히트 부울합니다 추가> 0 if() statment에있는 경우 .length 만 ... – dandavis

답변

3

이 시도해야합니다 :

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

} 
6

는 경우 조건에 넣어해서는 안된다. 아무것도 선택하지 않아도 항상 true입니다.

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

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

또는

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