jQuery循环遍历所有数据属性

5
我正在尝试在动画后重置数据属性,并且正在尝试应用来自这篇文章的第2个答案的技术,但遇到了一些问题。
不确定我错过了什么。 理论上说对于每个数据属性等都是可行的。
更新:
值得一提的是,数据键都是不同的。 例如,data-1 =“abc”data-2 =“abc”等,因此需要一个for循环,只查找data属性。

HTML

var total = 0;    
$.each($('*').data(), function(key, value) {        
    if (key){    
        var thiis = $(this);            
        total += key;            
        thiis.removeData();            
        thiis.data(total, value);
    }
});

1
需要更多细节!请发布你的HTML代码。 - Rajaprabhu Aravindasamy
1
$('*').data() 是问题所在...你需要定位到单个元素...所以把 * 改成其他东西。 - Arun P Johny
你是针对特定的数据属性还是全部进行目标定位? - Arun P Johny
@ArunPJohny 所有数据属性。刚刚编辑了帖子以作澄清。 - technopeasant
1
还有一个数据属性和data() API之间的区别...数据API可能使用data-*属性来初始化值,之后使用数据API进行的更改不会反映在属性中。 - Arun P Johny
显示剩余2条评论
1个回答

3

明白了,这个脚本有很多额外的开销,所以在用户等待的实例中运行它不是一个好的选择,我认为。你可以改进它,使用具体性代替*选择器。

JavaScript(jQuery):

var counter  = 1; // not necessary for your implementation, using it to adjust numeric data keys

$('*').each(function(){ // query all selectors and run through a loop

    var thiis    = $(this),
        dataAttr = thiis.data(),
        i;

    if (dataAttr) { // if the element has data (regardless of attribute)

        var newAttrs = []; // for the element's new data values

        $.each(dataAttr, function(key, value) { // loop through each data object

            var newKey  = key + counter, // calculate new data key
                newAttr = [newKey, value]; // push the new data set

            newAttrs.push(newAttr); // push to elements new attributes array

            thiis
                .removeData(key) // remove the data
                .removeAttr('data-' + key); // remvoe the attribute (unnecessary)
        });

        for (i = 0; i < newAttrs.length; i++) { // for each new attribute

            thiis.data(newAttrs[i][0], newAttrs[i][1]); // add the data
            thiis.attr('data-' + newAttrs[i][0], newAttrs[i][1]); // add the attribute (unnecessary)
        }
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接