jquery - 使用 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);
});
- [日志] rgb(255, 0, 0) #ff0000
- [日志] rgb(255, 165, 0) #ffa500
- [日志] rgb(255, 255, 0) #ffff00
- [日志] RGB(128, 0, 128) #800080
- [日志] rgb(0, 0, 255) #0000ff
解决方案
更改以下...
$("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>
推荐阅读
- reactjs - 为什么我的 scss 不能在 MacOS 上处理 react 项目
- php - 如何更改laravel中验证错误的键
- python - 将pandas系列的json对象转换为DataFrame
- python - 在numpy中交换下降条的轴
- c++ - 用 atomic bool 同步 10 个线程
- python - 下载和导入时的 TensorFlow 问题
- azure - 使用 ServiceBusTrigger 的 Azure 函数在 Xamarin.Android 应用程序中不起作用
- sql-server - 如何在选择子句中使用表值函数?
- node.js - 如何使用 OIDC (vuejs + nodejs) 对前端和后端进行身份验证?
- javascript - 基于用户选择的角度更改/替换字符串中的值