我有三组列。每列都有不同类型的数据属性名称和整数值。数据属性名称值将根据 div 的长度递增 500。
这是我的html结构,
<div class="column">
<div data-0="100"></div>
<div data-500="200"></div>
<div data-1000="300"></div>
</div>
<div class="column">
<div data-1500="400"></div>
<div data-{increase value from prev child}="{increase value from prev child}"></div>
<div data-increase value from prev child="{increase value from prev child}"></div>
<div data-{increase value from prev child}="{increase value from prev child}"></div>
<div data-increase value from prev child="{increase value from prev child}"></div>
</div>
<div class="column">
<div data-{increase value from prev child}="{increase value from prev child}"></div>
<div data-increase value from prev child="{increase value from prev child}"></div>
<div data-{increase value from prev child}="{increase value from prev child}"></div>
<div data-increase value from prev child="{increase value from prev child}"></div>
<div data-{increase value from prev child}="{increase value from prev child}"></div>
<div data-increase value from prev child="{increase value from prev child}"></div>
</div>
如何用jquery实现这个逻辑?
最佳答案
这是其中一种方法。查找内联评论。
//All columns
var $columns = $(".column");
//Grab the first div from the first column
var $firstColumnFirstChild = $columns.first().find("div").first();
//Grab the data attribute name (0) from '$firstColumnFirstChild' and convert it to number
var $firstColumnFirstChildKey = parseInt(Object.keys($firstColumnFirstChild.data()), 10);
//Set initial value
var $initial = 100;
//Go thru each div in all columns
$columns.find("div").each(function(_, elem) {
//Set data attribute (name and value)
$(elem).attr("data-" + $firstColumnFirstChildKey, $initial);
//Increment for future divs
$firstColumnFirstChildKey += 500;
$initial += 100;
});
这里是 a demo对于以上内容。
关于javascript - 如何在 jquery 中动态更改属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32561844/