首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么我的数组不能作为remove函数的参数?

为什么我的数组不能作为remove函数的参数?
EN

Stack Overflow用户
提问于 2019-05-21 05:51:14
回答 1查看 43关注 0票数 0

所以,我有一个页面,我可以在其中添加食物到订单列表中,目前我也正在进行“从列表中删除”功能,但我面临着一个问题。当我在右边的removeButton上调用setAttribute()时,我还想从数组中删除该项,这样它就不会将删除的食物的名称发送到数据库。我的问题如下:在setAttribute()的调用中,我的数组出了问题,因为removeName没有将其作为参数获取。

代码语言:javascript
复制
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);
}
EN

回答 1

Stack Overflow用户

发布于 2019-05-21 06:59:08

看起来你的问题可能出在这一行:

代码语言:javascript
复制
removeButton.setAttribute('onClick','removeName("'+'item'+lastid+', foods_added")');

我建议你试试这个:

代码语言:javascript
复制
removeButton.addEventListener('click', () => {
    removeName(`item${lastid}`, foods_added);
});

或者,如果您不能使用es6:

代码语言:javascript
复制
removeButton.addEventListener('click', function() {
    removeName('item' + lastid, foods_added);
});

更详细地解释代码不工作的原因,我想是因为作为第二个参数传递给setAttribute的字符串是在调用函数外部的上下文中求值的。foods_added不存在于该上下文中,因此它是未定义的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56228616

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档