[英]Why isn't my array good as a parameter for my remove function?
So, I have a page where I can add foods to an order list and currently I am making the "remove from the list" function as well, but I am facing a problem. 所以,我有一个页面,我可以将食物添加到订单列表中,目前我正在进行“从列表中删除”功能,但我遇到了问题。 When I call setAttribute() on the right removeButton, I also want to remove the item from my array so that it won't send the removed food's name to the database. 当我在右侧removeButton上调用setAttribute()时,我还想从数组中删除该项,以便它不会将删除的食物名称发送到数据库。 My problem is the following: In the call of setAttribute(), something is wrong with my array, because removeName doesn't get it as a parameter. 我的问题如下:在调用setAttribute()时,我的数组出了问题,因为removeName不会将它作为参数。
var lastid = 0;
var foods_added = [];
var locked = true;
function add_food() {
var food_name = document.getElementById('food_name').value;
$.ajax({
url: "ask-info.php",
type: "post",
data: { food_name : JSON.stringify(food_name) },
success: function(res) {
console.log(res);
if (res == "van") {
var entry = document.createElement('h4');
entry.appendChild(document.createTextNode(food_name));
entry.setAttribute('id','item'+lastid);
var removeButton = document.createElement('button');
removeButton.appendChild(document.createTextNode("Töröl"));
removeButton.setAttribute('onClick','removeName("'+'item'+lastid+', foods_added")');
entry.appendChild(removeButton);
lastid+=1;
list.appendChild(entry);
foods_added.push(food_name);
document.getElementById('food_name').value = "";
document.getElementById('press').disabled = true;
} else {
document.getElementById('press').disabled = true;
}
}
})
}
function removeName(itemid, foods_added){
var item = document.getElementById(itemid);
for (var i = 0; i<foods_added.length; i++) {
if (foods_added[i].id == itemid) {
foods_added.splice(foods_added[i].id, 1);
}
}
list.removeChild(item);
}
It looks like your problem is probably in this line: 看起来您的问题可能就在这一行:
removeButton.setAttribute('onClick','removeName("'+'item'+lastid+', foods_added")');
I'd recommend trying this instead: 我建议尝试这样做:
removeButton.addEventListener('click', () => {
removeName(`item${lastid}`, foods_added);
});
Or if you don't have the ability to use es6: 或者,如果您没有能力使用es6:
removeButton.addEventListener('click', function() {
removeName('item' + lastid, foods_added);
});
Going into more detail about why your code isn't working, I imagine it's because the string you're passing in as the second parameter to setAttribute is evaled in a context outside of your calling function. 详细了解您的代码无法正常工作的原因,我想这是因为您作为setAttribute的第二个参数传入的字符串在调用函数之外的上下文中被唤醒。 foods_added doesn't exist in that context so it is undefined. foods_added在该上下文中不存在,因此未定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.