首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery所有数据属性的每个循环

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

Stack Overflow用户
提问于 2014-01-20 06:34:15
回答 1查看 6.3K关注 0票数 5

我试图在动画之后重置数据属性,并在应用来自answer 2 of this post的技术时遇到了一些困难。

不知道我在这里错过了什么。对于eachdata属性等来说,理论上似乎是可行的。

更新:

值得一提的是,data键都是不同的。例如,data-1="abc"data-2="abc"等,因此需要一个简单地查找data属性的for循环。

HTML

代码语言:javascript
复制
var total = 0;    
$.each($('*').data(), function(key, value) {        
    if (key){    
        var thiis = $(this);            
        total += key;            
        thiis.removeData();            
        thiis.data(total, value);
    }
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-21 06:34:01

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

JavaScript (jQuery):

代码语言:javascript
复制
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)
        }
    }
});
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21227617

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档