2012-12-29 102 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 
    } 

});