0

我正在尝试将数组内的对象(称为 id)的属性值发送到函数,该函数将删除数组内的该对象。按钮由innerHTML创建,根据数组有多少个值,创建一个按钮,每个按钮删除数组中对应的对象。我有这个代码:

<script>
var ingredientsArray = [];
var contid = 0;

function ingredients(id, name, status) {
    this.id = id;
    this.name = name;
    this.status = status;
}

document.querySelector("#button").addEventListener('click', function () {

    var x = document.getElementById("List").value;
    var objectIngredient = new ingredients(contid, x, false);
    ingredientsArray.push(objectIngredient);
    localStorage.setItem('ingredientsArray', JSON.stringify(ingredientsArray));
    console.log(ingredientsArray);
    contid++;
    draw()
});

function draw() {
    document.querySelector('#list').innerHTML = '';
    document.querySelector('#list').innerHTML = '<ul>';
    for (var i = 0; i < ingredientsArray.length; i++) {
        var x = '';
        var clas = '';
        if (x == true) {
            x = 'checked="cheked"';
            clas = 'strike()'
        }
        document.querySelector('#list').innerHTML += '<li>' + ingredientsArray[i].name;
        document.querySelector('#list').innerHTML += '<input type="checkbox" + x>';
        document.querySelector('#list').innerHTML += '<button onclick="erase(i)">erase</button>';
        console.log(ingredientsArray[i].id);
        document.querySelector('#list').innerHTML += '</li>';
    }
    document.querySelector('#list').innerHTML += '</ul>';
}

function erase(i) {
    var index = ingredientsArray.indexOf(i);
    ingredientsArray.splice(index, 1);
}

但是当按下按钮时,控制台会说函数期望的值为空。有谁知道为什么?谢谢!

4

1 回答 1

0

看起来你可以稍微修改一下代码来让它工作,我试试这个:

<button onclick="erase(' + i + ')">erase</button>

...

function erase(index) {
    ingredientsArray.splice(index, 1);
}
于 2018-03-13T01:51:33.160 回答