2015-12-15 18 views
4

如何檢查父section是否有另一個具有特定數據屬性的「子」div?這裏是東西,我會做的事:檢查使用JQuery的父節中是否存在具有特定數據屬性的子div

if ($("#parent").children().data("child-nr").contains("1") == true) { 
 
    $("#parent").css('background-color', 'green'); 
 
} 
 
else { 
 
    $("#parent").css('background-color', 'red'); 
 
}
div { 
 
    width: 50px; 
 
    height: 50px; 
 
    background-color: lightblue; 
 
    float: left; 
 
    margin: 5px; 
 
    text-align: center; 
 
    vertical-align: middle; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
 
<section id="parent"> 
 
    <div data-child-nr="1"><p>N° 1</p></div> 
 
    <div data-child-nr="2"><p>N° 2</p></div> 
 
    <div data-child-nr="3"><p>N° 3</p></div> 
 
</section>

回答

7

只是目標元素,並檢查它是否存在通過檢查集合length

完全匹配1

if ($('#parent div[data-child-nr="1"]').length) { ... 

包含1

if ($('#parent div[data-child-nr*="1"]').length) { ... 

始於1

if ($('#parent div[data-child-nr^="1"]').length) { ... 

1

if ($('#parent div[data-child-nr$="1"]').length) { ... 
+0

這是有效的 「11」 和 「1」? –

+1

不,它僅適用於「1」,這是標題所要求的(特定數據屬性),即使問題中的代碼使用了一些不存在的「contains」方法 – adeneo

+0

@ParthTrivedi - 開心! – adeneo

1

結束,您可以使用>選擇檢查elment直接孩子和使用[data-attribute selector],比檢查結果是> 0喜歡:

代碼:

if ($('#parent>div[data-child-nr="1"]').length > 0) { 
    // div exists   --> yes 
    alert('ok') 
} 
else { 
    // div doesn't exists --> no 
    alert('nope') 
} 

演示:http://jsfiddle.net/xt80p2b0/

0

試試這個:

$("#parent>div").each(function(){ 

    if ($(this).attr('data-child-nr') === "1") { 
     // div exists   --> yes 
     alert('ok'); 
    } 
    else { 
     // div doesn't exists --> no 
     alert('nope'); 
    } 
}); 
相關問題