簡體   English   中英

如何在jQuery中動態更改屬性值?

[英]How to change attribute value dynamically in jquery?

我有三套專欄。 每列具有帶整數值的不同類型的數據屬性名稱。 數據屬性名稱值將根據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;
});

這是上面的演示

更新了具有要求的示例: https : //jsfiddle.net/ozvkdw1p/1/

$(function() {
    var $col = $(".column")
    //grab first attribute of first element, extract values
    var initAttr = $("div", $col).get(0).attributes[0]
    var initName = parseInt(initAttr.name.split("-")[1])
    var initValue = parseInt(initAttr.value)
    $("div", $col).each(function() {
        $(this).removeAttr(this.attributes[0].name) //remove first attribute
        $(this).attr("data-" + initName, initValue) //add attribute with correct values
        //increment values for next iteration
        initName += 500 
        initValue += 100
    })
})

從firts元素中獲取數據,然后使用遞增值更新其他元素

您可以使用AngularJS框架更輕松地存檔。 這樣很容易將javascript值與hmtl(-attributes,..)組合在一起

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM