繁体   English   中英

为什么我的数组不能作为我的删除函数的参数?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM