2014-01-20 57 views
4

我試圖重置動畫後的數據屬性,並通過應用answer 2 of this post的技術運行時遇到一些麻煩。jQuery每個循環的所有數據屬性

不知道我在這裏錯過了什麼。似乎理論上是可行的說爲eachdata屬性等


UPDATE:

值得一提的是,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); 
    } 
}); 
+1

更多細節需要!請發佈您的HTML。 –

+0

@RajaprabhuAravindasamy感謝您的回覆。我的應用程序中的HTML發生了變化,並且與帖子無關 - 只是尋找收集for循環中的所有數據屬性的理論答案 – technopeasant

+1

'$('*')。data()'是問題所在......您需要目標是一個單一的元素...所以把'*'改成別的東西 –

回答

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) 
     } 
    } 
});