遍历jQuery中的数组 [英] iterate over array in jquery
本文介绍了遍历jQuery中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试对从列表中选择项目的用户进行一些验证.我想通过检查<li>
是否已经在数组中来确保没有两次添加项.这是我正在尝试,但无法正常工作.
I'm trying to do some validation on a user selecting items from a list. I want to make sure an item is not added twice by checking if the <li>
is already in the array. This is what I'm trying and its not working.
$(".List").on("click", "li", function () {
var i = 0;
var checkArr = [];
var div = $("#AddedItems");
var parent = $(this).closest("ul");
var itemtoadd = parent.find("[data-id]").attr("data-id");
var name = parent.find("[data-name]").attr("data-name");
alert(itemtoadd + name);//checking
var itemtoadd = ("<li id = " + itemtoadd + " class = \"itemAdd\">" + name + "</li>");
checkArr.push(itemtoadd); //put one in to check against?
checkArr.forEach(item)
{
if (item == itemtoadd)
alert("this item has already been added");
else {
checkArr.push(itemtoadd);
alert(itemtoadd);
$(itemtoadd).appendTo(div);
}
}
// div.html(itemtoadd);
});
推荐答案
您在这里至少遇到三个问题:
You have at least three problems here:
- 您未正确使用
Array.forEach
-它具有接受项的功能. - 在进行检查之前,您要立即添加要查找的项目.您将始终遇到
alert
情况. - 您正在使用
checkArr
作为局部变量-每次输入该函数都会得到一个空数组.
- You aren't using
Array.forEach
correctly -- it takes a function that takes an item. - Immediately before you do your check, you're adding the item you're looking for. You will always hit the
alert
case. - You're using
checkArr
as a local variable -- you're getting an empty array each time you enter the function.
总而言之,您无需保留任何数组就可以实现您的目标.我相信您可以用以下方法替换从第一条警报开始的所有内容:
That all being said, you can accomplish your goal without keeping an array at all. I believe you can replace everything from your first alert down with this:
if ($('#' + itemtoadd, div).length == 0) {
itemtoadd = ("<li id = " + itemtoadd + " class = \"itemAdd\">" + name + "</li>");
div.append(itemtoadd);
}
else {
alert("this item has already been added");
}
这篇关于遍历jQuery中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文