jQuery 每个循环的所有数据属性

tec*_*ant 5 javascript each jquery attributes loops

我正在尝试在动画播放后重置数据属性,并且在应用本文答案 2 中的技术时遇到了一些问题。

不确定我在这里缺少什么。对于each data属性等来说,理论上似乎是可行的。


更新:

值得一提的是,data钥匙都是不同的。例如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);
    }
});
Run Code Online (Sandbox Code Playgroud)

tec*_*ant 3

繁荣,明白了。该脚本有很多开销,因此在用户等待的实例中运行它不是一个选择,IMO。您可以通过特异性而不是*选择器来改进它。

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)
        }
    }
});
Run Code Online (Sandbox Code Playgroud)