将对象数组中的值发送到JavaScript

时间:2018-03-13 01:46:26

标签: javascript arrays function getvalue

我正在尝试将数组内的对象(称为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);
}

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

1 个答案:

答案 0 :(得分:0)

看起来您可以稍微更改代码以使其正常工作,我试试这个:

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

...

function erase(index) {
    ingredientsArray.splice(index, 1);
}