所以,我有一个页面,我可以在其中添加食物到订单列表中,目前我也正在进行“从列表中删除”功能,但我面临着一个问题。当我在右边的removeButton上调用setAttribute()时,我还想从数组中删除该项,这样它就不会将删除的食物的名称发送到数据库。我的问题如下:在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);
}
发布于 2019-05-21 06:59:08
看起来你的问题可能出在这一行:
removeButton.setAttribute('onClick','removeName("'+'item'+lastid+', foods_added")');
我建议你试试这个:
removeButton.addEventListener('click', () => {
removeName(`item${lastid}`, foods_added);
});
或者,如果您不能使用es6:
removeButton.addEventListener('click', function() {
removeName('item' + lastid, foods_added);
});
更详细地解释代码不工作的原因,我想是因为作为第二个参数传递给setAttribute的字符串是在调用函数外部的上下文中求值的。foods_added不存在于该上下文中,因此它是未定义的。
https://stackoverflow.com/questions/56228616
复制相似问题