简体   繁体   English

jQuery选择具有A或B或C类的元素

[英]jQuery Selecting Elements That Have Class A or B or C

I working on something where I need two functions. 我在需要两个功能的地方工作。

1 - I need to look at a group of children under the same parent and based on a class name, "active", add that element's ID to an array. 1-我需要查看一组在同一父项下的孩子,并基于类名“ active”,将该元素的ID添加到数组中。

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

2 - I then iterate through all the children in another parent and for each element I want to find out if it has any class name that match the ids in the array. 2-然后,我遍历另一个父级中的所有子级,对于每个元素,我想找出它是否具有与数组中的ID相匹配的类名。

Does this element have class foo-a, foo-b or foo-d? 这个元素是否具有foo-a,foo-b或foo-d类?

For the first part, I'd use map and get : 对于第一部分,我将使用mapget

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

This gives you an array of id values (say, ['foo-a', 'foo-d'] ). 这为您提供了一组ID值(例如['foo-a', 'foo-d'] )。 You can then make a selector like .foo-a, .foo-b, .foo-c (the multiple selector ) using join : 然后,您可以使用join创建一个.foo-a, .foo-b, .foo-c之类的选择器多重选择器 ):

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

This makes a valid jQuery selector string, eg '.foo-a, .foo-d' . 这将生成一个有效的jQuery选择器字符串,例如'.foo-a, .foo-d' You can then use this selector to find the elements you want using find : 然后,您可以使用此选择器使用find查找所需的元素:

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

You can then do whatever you need to with activeEls . 然后,您可以使用activeEls做任何您需要做的事情。

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();
       }
   });
});

There's always .is('.foo-a, .foo-b, .foo-d') . 总是有.is('.foo-a, .foo-b, .foo-d') Or if you actually just wanted to select them, instead of iterating and deciding for each element, $('.foo-a, .foo-b, .foo-d', startingPoint) . 或者,如果您实际上只是想选择它们,而不是为每个元素进行迭代和决定,则使用$('.foo-a, .foo-b, .foo-d', startingPoint)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM