javascript - 检查每个 div 是否有一个元素,里面有一个特定的类

标签 javascript jquery html function

我有一个 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/

相关文章:

javascript - 如何在进度条上显示步骤描述?

javascript - 类似 ios 的动画,可将内容从右向左滑动

javascript - 如果单击导航栏 ID,则 jQuery Mobile 发出警报

javascript - 数据表ajax从新来源重新加载

javascript - 如何在每 1 秒重复 1 分钟后停止 setTimeout

jquery - 将鼠标移到主菜单上不会使子菜单保持打开状态

html - CSS 网格布局 - 将 <p> 与输入字段对齐

javascript - 如何将大型 HTML 代码转换为字符串以便在 .innerHTML 中使用

javascript - 通过 JavaScript 将表格插入 div

javascript - 批量更新,txt文件名第三行内容(第三行内)