javascript - jQuery 每次循环所有数据属性

标签 javascript jquery loops attributes each

我试图在动画后重置数据属性,但在应用 answer 2 of this post 中的技术时遇到了一些麻烦.

不确定我在这里遗漏了什么。对于 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);
    }
});

最佳答案

砰,明白了。该脚本有很多开销,因此在用户将等待通过的实例中运行它不是一种选择,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)
        }
    }
});

关于javascript - jQuery 每次循环所有数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21227617/

相关文章:

java - 为什么这个 while 循环不能每秒打印 1,000 次?

python - 如何让这个程序在 Python 中绘制 10 个椭圆?

javascript - TypeScript:替换现有类型

php - 将站点访问限制为仅 QR 扫描

javascript - casperjs click() 标签如何不是 anchor

javascript - Firefox - 按键错误。不能仅对字母输入脚本使用退格键

jquery - overflow-y 滚动和弹出窗口中的溢出隐藏问题

php - jQueryUI 自动完成 : Returning data from multiple columns in a MySQL database and joining them

jquery - 使用动态表单的 ASP.Net MVC 3 客户端验证

java - 在Java中创建数字矩阵