2010-05-11 17 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