2010-05-11 18 views
2

我有许多要作为组进行循环的元素。考虑这个HTML:用于分组迭代的CSS选择器

<input class="matching match-1" /> 
<input class="matching match-1" /> 
<input class="matching match-2" /> 
<input class="matching match-2" /> 
<input class="matching match-2" /> 
<input class="matching match-3" /> 
<input class="matching match-3" /> 
// etc 

我希望有一个CSS选择器,让我来遍历这些作为组,这样就不会有 - 用这个例子 - 循环3次迭代(一个用于比赛-1,一个用于比赛-2和一个用于比赛-3)。 1,2,3等是一个用于分组的变量,但这不是固定的,所以不能依赖这些值的硬编码。这甚至有可能吗?我将使用jQuery或原型而不是那真的应该重要。

感谢

回答

4

试试这个:

var groups = []; 
$(".matching").each(function(index, elem) { 
    if (this.className.match(/(?:^|\s+)match-(\d+)(?:\s|$)/)) { 
     if (typeof groups[RegExp.$1] == "undefined") { 
      groups[RegExp.$1] = []; 
     } 
     groups[RegExp.$1].push(this); 
    } 
}); 

这会遍历元素列表与类匹配,测试,如果它也有一类的表格match-x,获取x并将其添加到使用x作为索引的匹配组列表。

0

编辑

for(i=0;i<3;i++){ 
    var str = ".matching-match-" + i; 
     $(str).each(function(index) { 
      //do something 
      }); 
    } 

我希望我理解正确的UR问题。这是你的Lukin吗?

+0

嗯...是不会让他循环中的所有投入。 – Cristian 2010-05-11 20:50:50

+0

nope,“1,2,3等是一个变量用于分组,但这是不固定的,因此它不能依靠这些值的硬编码” – robjmills 2010-05-11 20:51:16

0
max = parseInt($('.matching:last-child').attr('class').match(/d+/)[0]); 
for(i = 1; i <= max; i++) { 
    $els = $('.matching.match-'+i.toString()); 
    // do whatever you want on the group 
} 
+0

对不起,如果我不清楚,但不能保证'我'将是<= 3 – robjmills 2010-05-11 20:55:30

+0

我使用第一行来解决该问题。 – 2010-05-11 20:56:09

1

在标准的CSS2(也就是目前广泛支持的实现)中,没有任何东西可以描述为可用。

但是,CSS3具有更灵活的选择器,幸运的是,它们都是在jQuery中实现的。

尝试这样:

$("input[name^='match-']") 

这将返回匹配你正在试图做什么DOM节点的一个jQuery集合。你可以使用经典的JS或jQuery的.each()迭代。

+0

不幸的是,只会创建所有列出的元素的单个集合,虽然没有所需的分组 – robjmills 2010-05-11 20:54:24

0

input[class^="matching match-"]应该工作。我不确定你的意思是分组。

编辑:

var groups = []; 
var classes = {}; 
$('input[class^="matching match-"]').each(function() { 
    classes[$(this).attr('class')] = 1; 
}); 
for (c in classes) { 
    groups.push($('input[class="'+c+'"]')) 
} 
+0

我的意思是组,因此所有具有 - 例如 - 一类匹配-1的输入都被视为1组,因此给定在$('selector_i_want')。length == 3'之上的HTML – robjmills 2010-05-11 20:58:16

0

这可能是工作。没有时间来测试它虽然XD

var count = 1; 
var alreadyCounted = new Array(); 
$(".matching").each(function(){ 
    if(typeof alreadyCounted[count] == 'undefined'){ 
     $('.match-'+count).each(){ 
      // DWTFYW 
     } 
     alreadyCounted[count] = true; 
    } 
    count++; 
}); 
0

这将建立群组列表:

var classList = [] 
    $('.matching').each(function(i,e) { 
     var myClasses = ($(e).attr('class')).split(" ") 
     classList[myClasses[1]] = true  
    }) 

    for (index in classList) { 
     alert(index) 
     //your code here 
    } 
1

使用jQuery:

var indices = {}; 
var index; 

$('.matching').each(function() { 
    index = $(this).attr('class').match(/\d+$/); 
    indices[index] = index; 
}); 

// Now you have a unique list of matching numbers for your loops