繁体   English   中英

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.grepjQuery.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM