2010-11-16 94 views
1

我基本上有一個名爲findItem()的小函數,它應該根據元素上的自定義data-屬性來查找我正在查找的元素。jQuery:如何遍歷一組元素,找到與其他數組中的值匹配的元素?

在這種情況下,這些純粹是數字例如。 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]) 

不工作,因爲count if語句似乎並不匹配任何內部。

頁面確實包含4個<li data-slide="{number}">…元素,所以1,3應返回這些元素的第一個和第三個。

我在這裏做錯了什麼?

回答

5

使用jQuery.grepjQuery.inArray

function findItem(items) { 
    return jQuery.grep($('li'), function(element, index) { 
     return jQuery.inArray($(element).data('slide'), items) != -1; 
    }); 
} 

Working example

+0

嗯...我複製/粘貼到我的文件中,但註銷'findItem([1,3])'的結果'返回第三次'li'而不是第一次和第三次'li'每次一次。任何想法我做錯了什麼? – Jannis 2010-11-16 19:25:41

+0

@Jannis,試試我更新的答案,我也提供了一個關於jsFiddle的例子。 – 2010-11-16 19:51:30

+0

我檢查了我們的小提琴,但只要你添加更多'li's它打破仍然,看到我更新的小提琴在這裏:http://jsfiddle.net/UVFBu/1/ – Jannis 2010-11-16 20:10:03

1

以修正,如果statment不匹配任何內部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]) 
+0

謝謝,但它仍然不會因爲'裏面count'匹配if語句整個數組,而不是單個數字再次匹配。所以在if語句中計數的是[1,3,4],它不是'== 1',這是if語句要求的。 – Jannis 2010-11-16 05:31:49

+0

對不起Jannis,在我更新它時,你一定寫了你的評論。下半年應該解決你的問題。 – 2010-11-16 05:33:00

+0

是的,我確實。我應用了您的更新解決方案,並且效果很好。非常感謝。 – Jannis 2010-11-16 19:27:46

相關問題