【问题标题】:jQuery each loop of all data attributesjQuery所有数据属性的每个循环
【发布时间】:2014-02-09 05:54:15
【问题描述】:

我正在尝试在动画后重置数据属性,但在应用 answer 2 of this post 的技术时遇到了一些问题。

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


更新:

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

HTML

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

【问题讨论】:

  • 需要更多细节。!请发布您的 html。
  • @RajaprabhuAravindasamy 感谢您的回复。我的应用程序中的 HTML 发生了变化,与帖子无关 - 只是在寻找关于在 for 循环中收集所有数据属性的理论答案
  • $('*').data() 是问题...您需要定位单个元素...所以将* 更改为其他内容
  • 您是针对特定数据属性还是所有...
  • data 属性和data() api 之间也有区别... data api 可能会使用data-* 属性来初始化值,之后使用 data api 所做的更改将不会体现在属性中

标签: javascript jquery loops attributes each


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    相关资源
    最近更新 更多