2011-08-31 93 views
2

我工作的地方需要兩個功能。jQuery選擇具有A類或B類或C類的元素

1 - 我需要查看同一父項下的一組子項,並根據類名「active」將該元素的ID添加到數組中。

['foo-a','foo-b','foo-d'] 

2 - 然後我通過另一個父和我想找出它是否在數組中匹配的IDS,任何類名的每個元素的所有孩子進行迭代。

此元素是否具有類foo-a,foo-b或foo-d?

回答

2
var active = $("#foo").find(".active").map(function() { 
    return this.id; 
}).get(); 

$("#anotherParent *").each(function() { 
    var that = this; 
    var classes = $(this).attr("class"); 
    if(classes.indexOf(" ") !== -1) { 
     classes = classes.split(" "); 
    } else { 
     classes = [ classes ]; 
    } 
    $.each(classes, function(i, val) { 
     if($.inArray(val, active)) { 

      // this element has one of 'em, do something with it 
      $(that).hide(); 
     } 
    }); 
}); 
1

總是有.is('.foo-a, .foo-b, .foo-d')。或者如果你只是想選擇它們,而不是迭代和決定每個元素,$('.foo-a, .foo-b, .foo-d', startingPoint)

3

在第一部分,我會使用mapget

var activeGroups = $('#parent .active').map(function() { 
    return this.id; 
}).get(); 

這給你的ID值(比方說,['foo-a', 'foo-d'])的陣列。然後,您可以使用join.foo-a, .foo-b, .foo-c選擇(在multiple selector):

var activeSelector = '.' + activeGroups.join(', .'); 

這使得一個有效的jQuery選擇的字符串,例如'.foo-a, .foo-d'。然後,您可以使用此選擇找到你想要使用find元素:

var activeEls = $('#secondParent').find(activeSelector); 

然後你可以做任何你需要與activeEls