javascript - 如何在 jquery 中动态更改属性值?

标签 javascript jquery html

我有三组列。每列都有不同类型的数据属性名称和整数值。数据属性名称值将根据 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/

相关文章:

javascript - Jquery 日期选择器 - 想要在输入字段中显示日期

javascript - HTML 和 JQuery : How to create slideshow of images or text?

html - Bootstrap 在 WAMP 服务器上不工作

javascript - 用数字在表格中用逗号替换点

javascript - 如何在 React Native 项目中使用 Node.JS 中的 Crypto 内置模块?

jquery - 悬停时淡化投资组合图像以显示放大镜或加号等?

javascript - 加载页面片段时 jQuery load(URL) 不起作用?

html - 表格行有边框但中间有间距

javascript - 选项卡内的复选框切换 Bootstrap

javascript - 希望在互联网出现故障时离线存储表单数据并在互联网活跃时提交