开发者

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.

In this case these are pure开发者_如何学编程ly numerical eg. 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.

The page does contain 4 <li data-slide="{number}">… elements so 1,3 should return the first and third of those elements.

What am I doing wrong here?


Use jQuery.grep and jQuery.inArray:

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

Working example


To fix the issue with the count inside the if statment not matching anything, try this:

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.

Your second issue is the fact that you're passing count as an array. So the if condition needs a little fixing:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜