2012-12-29 100 views
5

我有很多同一班級的元素。這些元素通過屬性的「數據XXX」方式分爲團體爲每個班級運行一次,但爲組運行一次​​

<div class="myclass" data-n="group1"></div> 
<div class="myclass" data-n="group1"></div> 
<div class="myclass" data-n="group1"></div> 
.... 
<div class="myclass" data-n="group2"></div> 
<div class="myclass" data-n="group2"></div> 
... 
<div class="myclass" data-n="group3"></div> 
... 
... 

如何在每個項目上使用這樣的事情每個組中執行功能,但只有一次?

$('.myclass').each(function(){ 

/// My function 

}); 
+0

我不認爲jquery有一個選擇器來說明數據屬性。 – 2012-12-29 01:48:31

+1

@DanMayor - 當然,你可以:http://jsfiddle.net/userdude/nzgyT/ –

+0

@DanMayor使用選擇也與這一問題無關 – charlietfl

回答

3

工作例如:http://jsfiddle.net/5sKqU/1/

$(document).ready(function() { 
    var group = {}; //an object that we're going to use as a hash 
    $('.myclass').each(function(){ 
     if (group[$(this).attr('data-n')] != true) { 
      group[$(this).attr('data-n')] = true; 

      //do something here once per each group 
      alert('Group: '+ $(this).attr('data-n')); 
     } 
    }); 
}); 

我假設你只需要這個網頁加載運行一次。如果您可以分享更多關於您的要求,我可以告訴您需要做出哪些更改。

+0

+1雖然我可能會使用[數組](http://jsfiddle.net/5sKqU/2/)。 ; p –

+0

這個決定在我看來是最引人注目的!感謝您的幫助! – Aleksov

0

您可以用jQuery的屬性選擇器中選擇出各組,就像這樣:

$('.myclass[data-n="groupX"]'); 

我不知道,如果你的意思,你只希望你的函數應用於一個要素每個組中,但如果是這樣,這將讓你只在每個第一:

$('.myclass[data-n="groupX"]').first(); 

既然你標記您的組1至N你可以檢查是否有在生成的設置,以確定您已經通過各組循環東西。

+0

從選擇器中刪除空間 – charlietfl

1

事情是這樣的,也許:

var groups = {}; 
$('.myclass').each(function(i, el) { 
    var n = $(el).data('n'); 
    if(!groups[n]) { 
     groups[n] = $(); 
    } 
    groups[n] = groups[n].add(el); 
}); 

//At this point the object `groups` has one property per group, 
//each value being a jquery collection comprising members of the group. 

//Now the world's your oyster. You can loop through the groups 
//with full access to each group's members if necessary. 
$.each(groups, function(groupName, jq) { 
    //my function 
}); 
1

可以處理後的第一個設置所有族元素一定的HTML屬性。之後,您可以檢查該屬性的值:

$('.myclass').each(function(){ 

    if($(this).attr("processed")!="true") { 
     // process... 
     $("[data-n=" + $(this).attr("data-n")).attr("processed", "true"); 
    } else { 
    // skip, or do something else with the element 
    } 

});