为一个类运行每个,但对于组运行一次

时间:2012-12-29 01:43:37

标签: javascript jquery dom

我有很多同一类的元素。这些元素通过属性“ data-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

});

4 个答案:

答案 0 :(得分: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'));
        }
    }); 
});

我假设您只需要在页面加载时运行一次。如果您可以分享更多有关您的要求的信息,我可以向您展示您需要做出哪些更改。

答案 1 :(得分: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
});

答案 2 :(得分: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
  }

});

答案 3 :(得分:0)

您可以使用jQuery属性选择器选择每个组,如下所示:

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

我不确定你是否意味着你只是想将你的功能应用到每个组中的一个元素,但是如果是这样的话,这将只给你每个元素中的第一个:

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

鉴于您将组1至N标记为标记,您只需检查结果集中是否有任何内容,以确定何时循环每个组。