Javascript jQuery.inArray始终返回-1
我有以下购物清单 我希望每次用户点击垃圾桶时,都能将产品从列表中删除。 所以我有这个:Javascript jQuery.inArray始终返回-1,javascript,jquery,undefined,Javascript,Jquery,Undefined,我有以下购物清单 我希望每次用户点击垃圾桶时,都能将产品从列表中删除。 所以我有这个: $(document).ready(function() { var selectedproducts = new Array(); //List of selected products $("#add_product_button").button(); $("#add_product_button").click(function() { //Add some products t
$(document).ready(function() {
var selectedproducts = new Array(); //List of selected products
$("#add_product_button").button();
$("#add_product_button").click(function() {
//Add some products to selectedproducts
//Omitted for clarity
selectedproducts[i]=document.getElementById("autocomplete_text_field").value;
thesi=jQuery.inArray(document.getElementById("autocomplete_text_field").value,selectedproducts);
var row=$('<div class"productsclass" style="height:50px; background-color:#E36D84; -webkit-border-radius: 5px; border-radius: 5px; border-style:solid; border-color:#DB4865; id='+rowID+'" ><label style="position:relative; top:10px; left:2px; font-size:20px">'+selectedproducts[i]+'</label><input style="position:relative; left:2px; top:10px; width:20px;" type="text" name="Quantity" value="1"><img class="delete" id="'+rowID+'" src="http://b.dryicons.com/images/icon_sets/handy_part_2_icons/png/128x128/recycle_bin.png" height="22" width="22" style="position:relative; top:10px; float: right;"></div><br>');
rowID++;
$("#productstable").append(row);
i++;
console.log("Thesi: "+thesi+" Timi:"+document.getElementById(thesi).value);
});
//Delete products
$(document).on("click", "[class*='delete']", function(s) {
thisID = $(this).attr('id'); //find items parent
console.log("ThisID: "+thisID);
console.log(jQuery.inArray(thisID,selectedproducts));//find item's position in the selectedproducts
selectedproducts.splice(thisID,1);
$(this).parent().hide("explode", 1000);
$(this).parent().remove();//delete item
console.log("Size:"+selectedproducts.length);
console.log(selectedproducts);
});
});
你知道我的问题出在哪里吗?你的要求
thesi=jQuery.inArray(thisID,selectedproducts);
但是
没有定义。还是我遗漏了什么?为什么
[class*='delete']
而不是简单的.delete
?你能不能也发布购物清单的HTML?@limelights-这是个问题,因为…:-@阿尔瓦罗格·维卡里奥我的设置有问题,对此我深表歉意!(1) selectedproducts[i]
表明我们处于循环中,但没有循环,i
未初始化!与rowID
相同。(2) document.getElementById(thesi)
建议thesi
是一个元素id,但它被设置为$.inArray()返回的值,即一个整数。(3) 当jQuery显然可用时,为什么要使用document.getElementById()
?(4) 当您可以分配值时,为什么重复document.getElementById(“自动完成文本字段”).value
?(5) thesi
和thisID
是否有意全局化,如果是,原因是什么?我建议,这里有很多问题需要解决。与jQuery.inArray(document.getElementById(“autocomplete\u text\u field”))相同。值pnames
:-?在同一个函数中定义。如果我执行console.log(selectedproducts)
数组是在控制台中打印的。我将发布所有我正在为同一个问题苦苦挣扎的函数。看起来inArray和indexOf并不是数字数组或请求的超级粉丝。使用关键字而不是数字似乎效果更好。@lvaroG.Vicario我想现在可以了。更多信息,请省略代码clarity@AvraamMavridis-你“我们隐藏了向selectedproducts
添加项目的部分。如果我们不知道selectedproducts
包含哪些内容,我们如何说明查找失败的原因?”?
thesi=jQuery.inArray(thisID,selectedproducts);
selectedproducts