[英]Why isn't my array good as a parameter for my remove function?
所以,我有一個頁面,我可以將食物添加到訂單列表中,目前我正在進行“從列表中刪除”功能,但我遇到了問題。 當我在右側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);
}
看起來您的問題可能就在這一行:
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在該上下文中不存在,因此未定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.