[英]jQuery: How can I loop over a set of elements finding only those matching the values within another array?
I've basically got a little function called findItem()
that is supposed to be finding the elements I'm looking for based on custom data-
attributes on the element. 我基本上有一个名为findItem()
的小函数,该函数应该根据元素上的自定义data-
属性来查找我要查找的元素。
In this case these are purely numerical eg. 在这种情况下,这些都是纯数字形式的。 data-slide=1
. data-slide=1
。
I'm a bit clueless as to how to match the value of each item's data-slide to one that is contained within the other array. 我对如何将每个项目的数据幻灯片的值与另一个数组中包含的数据幻灯片的值一无所知。
Here is a more concrete example: 这是一个更具体的示例:
function findItem(count) {
var collection = [];
$.each(allMyLiItems, function(i, item) {
if ( $(item).data('slide') == count ) {
collection.push(item);
}
});
return $(collection);
}
findItem([1,3])
which does not work because count
inside the if statement does not seem to match anything. 这不起作用,因为在if语句中count
似乎与任何内容都不匹配。
The page does contain 4 <li data-slide="{number}">…
elements so 1,3 should return the first and third of those elements. 该页面确实包含4个<li data-slide="{number}">…
元素,因此1,3应该返回这些元素的第一个和第三个。
What am I doing wrong here? 我在这里做错了什么?
Use jQuery.grep
and jQuery.inArray
: 使用jQuery.grep
和jQuery.inArray
:
function findItem(items) {
return jQuery.grep($('li'), function(element, index) {
return jQuery.inArray($(element).data('slide'), items) != -1;
});
}
To fix the issue with the count
inside the if statment not matching anything, try this: 要解决if语句中的count
不匹配的问题,请尝试以下操作:
function findItem(count) {
var collection = [],
count = count;
$.each(allMyLiItems, function(i, item) {
if ( $(item).data('slide') == count ) {
collection.push(item);
}
});
return $(collection);
}
findItem([1,3])
This will create a closure so the anonymous function inside the each
will be able to see it. 这将创建一个闭包,因此each
闭包中的匿名函数将能够看到它。
Your second issue is the fact that you're passing count
as an array. 第二个问题是您将count
作为数组传递。 So the if
condition needs a little fixing: 因此, if
条件需要一些修复:
function findItem(count) {
var collection = [],
count = count;
$.each(allMyLiItems, function(i, item) {
if ( count.indexOf($(item).data('slide')) !== -1 ) {
collection.push(item);
}
});
return $(collection);
}
findItem([1,3])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.