首页 > 解决方案 > 使用 jQuery 迭代每个 div 属性?

问题描述

我正在尝试获取每个 div 的 rgb 和索引值。在控制台中,我得到了正确的一切(每个 div 的索引和 B 背景颜色)。尝试将每个值添加到每个 div 中的p只有每个div重复的最后一个值:蓝色的十六进制和数字 5。我该如何解决?

.red {
    background-color:red; 
}.orange {
    background-color:orange; 
}
.yellow {
    background-color:yellow; 
}
.purple {
    background-color:purple; 
}
.blue {
    background-color:blue; 
}
<div class="red"><p></p></div>
<div class="orange"><p></p></div>
<div class="yellow"><p></p></div>
<div class="purple"><p></p></div>
<div class="blue"><p></p></div>

$('div').each(function(index) {
  var x = $(this).css('background-color');
  $("div p").text(index+x);
  console.log(index+x);
});

标签: jqueryhtml

解决方案


更改以下...

$("div p").text(index+x);

至...

$(this).find("p").text(index+x);

目前您正在<div>再次找到所有元素,并在每个元素中填充<p>...这就是为什么您会看到所有元素的最终值

$('div').each(function(index) {
  var x = $(this).css('background-color');
  $(this).find("p").text(index+x);
  console.log(index+x);
});
.red {
    background-color:red; 
}.orange {
    background-color:orange; 
}
.yellow {
    background-color:yellow; 
}
.purple {
    background-color:purple; 
}
.blue {
    background-color:blue; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="red"><p></p></div>
<div class="orange"><p></p></div>
<div class="yellow"><p></p></div>
<div class="purple"><p></p></div>
<div class="blue"><p></p></div>


推荐阅读