![](/img/trans.png)
[英]How can I loop through a set of IDs and match the active element's attribute of another set of elements in jQuery?
[英]jQuery: How can I loop over a set of elements finding only those matching the values within another array?
我基本上有一個名為findItem()
的小函數,該函數應該根據元素上的自定義data-
屬性來查找我要查找的元素。
在這種情況下,這些都是純數字形式的。 data-slide=1
。
我對如何將每個項目的數據幻燈片的值與另一個數組中包含的數據幻燈片的值一無所知。
這是一個更具體的示例:
function findItem(count) {
var collection = [];
$.each(allMyLiItems, function(i, item) {
if ( $(item).data('slide') == count ) {
collection.push(item);
}
});
return $(collection);
}
findItem([1,3])
這不起作用,因為在if語句中count
似乎與任何內容都不匹配。
該頁面確實包含4個<li data-slide="{number}">…
元素,因此1,3應該返回這些元素的第一個和第三個。
我在這里做錯了什么?
使用jQuery.grep
和jQuery.inArray
:
function findItem(items) {
return jQuery.grep($('li'), function(element, index) {
return jQuery.inArray($(element).data('slide'), items) != -1;
});
}
要解決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])
這將創建一個閉包,因此each
閉包中的匿名函數將能夠看到它。
第二個問題是您將count
作為數組傳遞。 因此, 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.