我有一个 div
元素树,具有相同的 class
但不同的 id
如下所示:
<div class="resultsAnalitics" id="result_0">
<span class="successResults">Success</span>
</div>
<div class="resultsAnalitics" id="result_1">
<span class="warningResults">Warning</span>
</div>
<div class="resultsAnalitics" id="result_2">
<span class="dangerResults">Danger</span>
</div>
我必须检查每个 div 中存在哪个类并显示在控制台上。为此,我创建了以下代码:
$( ".resultsAnalitics" ).each(function( index ) {
var current = $(this).attr('id');
console.log("I'm on div: " + current);
if($(this).has('.successResults')){
console.log('The results is success');
}
if($(this).has('.warningResults')){
console.log('The results is warning');
}
if($(this).has('.dangerResults')){
console.log('The results is danger');
}
});
我希望得到如下结果:
I'm on div: result_0 The results is success
I'm on div: result_1 The results is warning
I'm on div: result_2 The results is danger
但我得到以下结果:
I'm on div: result_0 The results is success The results is warning The results is danger
I'm on div: result_1 The results is success The results is warning The results is danger
I'm on div: result_2 The results is success The results is warning The results is danger
我该如何解决这个问题?
最佳答案
一个高效的解决方案是使用.children
方法,因为你必须检查每个
div 的span
children 是否有一个特定的类
。
children
method gets the children of each element in the set of matched elements, optionally filtered by a selector.
$( ".resultsAnalitics" ).each(function( ) {
var current = $(this).attr('id');
console.log("I'm on div: " + current);
if($(this).children('.successResults').length){
console.log('The results is success');
}
if($(this).children('.warningResults').length){
console.log('The results is warning');
}
if($(this).children('.dangerResults').length){
console.log('The results is danger');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="resultsAnalitics" id="result_0">
<span class="successResults">Success</span>
</div>
<div class="resultsAnalitics" id="result_1">
<span class="warningResults">Warning</span>
</div>
<div class="resultsAnalitics" id="result_2">
<span class="dangerResults">Danger</span>
</div>
关于javascript - 检查每个 div 是否有一个元素,里面有一个特定的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42283632/