简体   繁体   中英

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. 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.

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:

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. foods_added doesn't exist in that context so it is undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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