[英]How to select elements with a specific array length
In an each function , I search through the DOM for many elements with a specific className . 在每个函数中 ,我在DOM中搜索具有特定className的许多元素。 This ClassName, according to its length, will create an array that is long 2 or 4.
根据其长度,此ClassName将创建一个长2或4的数组 。
I need to select these two type of element separately in order to act differently. 我需要分别选择这两种类型的元素,以便采取不同的行动。
How can I do that? 我怎样才能做到这一点?
<div class="foo-1"></div>
<div class="foo-1"></div>
<div class="foo-1-boo-2"></div>
jQuery jQuery的
$( '[class*=foo-]' ).each(function() {
var foo = $( this );
var fooArray = foo.attr( 'class' ).split( '-' );
var arrayLength = fooArray.length;
});
the console will return that there are 3 elements , two of them have length 2 and one 4 . 控制台将返回3个元素 ,其中两个元素的长度为2 ,一个元素的长度为4 。
I need to separate these two results in order to act differently as they were variables. 我需要将这两个结果分开,以使它们的行为有所不同,因为它们是变量。
I need something like: 我需要类似的东西:
var caseA = (foo with an arrayLength === 2);
var caseB = (foo with an awwayLength === 4);
One possible way is to use .filter
method with a function as an argument: 一种可能的方法是将
.filter
方法与函数一起用作参数:
var elements = $('[class*=foo-]'),
caseA = elements.filter(function() {
return this.className.split('-').length === 2;
}),
caseB = elements.filter(function() {
return this.className.split('-').length === 4;
});
console.log(caseA.length, caseB.length);
I'm guessing you want these as jQuery sets instead of arrays so you can easily manipulate them en masse with jQuery. 我猜想您希望将它们作为jQuery集而不是数组,以便您可以轻松地与jQuery一起操作它们。 So this will do it:
所以这样做:
var caseA = $('[class*=foo-]').filter(function() {
return $(this).attr("class").split("-").length === 2;
});
var caseB = $('[class*=foo-]').filter(function() {
return $(this).attr("class").split("-").length === 4;
});
If you have tons of elements and it proves to be slow you can optimize this slightly by making it more complex and using one each
instead of filter. 如果您有大量的元素并且事实证明它很慢,则可以通过使其更加复杂并使用
each
元素而不是过滤器来对其进行稍微优化。 But I wouldn't bother until it proves to be necessary. 但是,除非证明有必要,否则我不会打扰。
Another possible way is to just use a conditional statement - 另一种可能的方法是只使用条件语句-
$('[class*=foo-]').each(function () {
var foo = $(this);
var fooArray = foo.attr('class').split('-');
var arrayLength = fooArray.length;
(2 == arrayLength ? console.log('to do something') : '');
(4 == arrayLength ? console.log('do something for') : '');
});
I mixed two solutions in the comment of this post: 我在这篇文章的评论中混合了两种解决方案:
var caseA = col.filter(function() {
return this.className.split( '-' ).length === 2;
});
var caseB = col.filter(function() {
return this.className.split( '-' ).length === 4;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.