我有一个看起来像这样的数组:
var testArr = ["40", "A1", "B9", "58"]
我想循环遍历某个类的所有div元素,并仅返回data属性与该数组中任何项目匹配的元素。
如果我这样做:
$("div.prodCodes").filter(function(e) {
var x1 = $(this);
var x2 = $(this).data("prodCode");
testArr.forEach(function(e) { if (e == x2) { console.log("MATCH"); } });
});
该控制台输出正确数量的匹配项,但我不能从过滤器函数返回这些元素。
我到底想念的是什么?我尝试过创建一个新数组并将每个项目推到它上面并返回那个,但它总是空的。我确定我在这里遗漏了一些明显的东西。我也试过用.grep()重写这个并且无处可去。感谢帮助。
答案 0 :(得分:1)
您需要在filter()
中返回真值以包含项目。
尝试:
$("div.prodCodes").filter(function(e) {
return testArr.indexOf($(this).attr('data-prodCode')) >-1;
}).doSomething();
如果没有return
,则会排除所有项目
答案 1 :(得分:0)
我会使用Set
进行恒定时间查找。
请注意jQuery读取属性值" 58"使用data
方法时的数字,因此除非您确保数据类型相同,否则它不会匹配:
// Use a set
var testSet = new Set(["40", "A1", "B9", "58"]);
var texts = $("div.prodCodes").filter(function() {
var x = $(this).data("prodCode").toString(); // data type must match
// Return a boolean to indicate whether the div element should be kept
return testSet.has(x); // Set#has() is fast
}).map(function(){
// For demo only: get the text content of the matching div elements
return $(this).text();
}).get(); // convert that to a plain array
console.log(texts);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="prodCodes" data-prod-code="A1">Hello</div>
<div class="prodCodes" data-prod-code="XX">Not this one</div>
<div class="prodCodes" data-prod-code="58">There</div>
&#13;