jQuery检查,添加或更新数组对象项

时间:2015-09-02 14:18:15

标签: jquery checkbox

我有一系列复选框和更改事件,如下所示:

$(".checkbox").on('change', function () {
          UpdateHolder($(this).attr('id'), customerID, this.checked);
});


function UpdateHolder(questionid, customerid, checked) {
        holder.push({ questionid: questionid, customerid: customerid, checked: checked });
        console.log(holder);
    }

有了这个,我可以在数组中添加一个项目,但我的问题是如何更新项目?我只想更新是否选中了复选框。

2 个答案:

答案 0 :(得分:1)

实现此目的的最简单方法是根本不更新列表,而是在每个操作上创建一个新列表。试试这个:

$('.checkbox').on('change', function() {  
    holder = $('.checkbox').map(function() {
        return { 
            questionid: this.id,
            customerid: customerID, // I presume this is a global variable?
            checked: this.checked
        };
    }).get();
    console.log(holder);
});

答案 1 :(得分:0)

为了能够更新现有条目,您的功能应如下所示:

function UpdateHolder(questionid, customerid, checked) {
    var index = holder.indexOf({
        questionid: questionid,
        customerid: customerid,
        checked: checked
    });
    index = index > -1 ? index : holder.indexOf({
        questionid: questionid,
        customerid: customerid,
        checked: !checked
    });
    //item was not found, insert it
    if( index < 0 ) {
        holder.push({ 
            questionid: questionid, 
            customerid: customerid, 
            checked: checked 
        });
    //item was found, update it
    } else {
        holder[index] = {
            questionid: questionid,
            customerid: customerid,
            checked: checked
        };
    }
    console.log(holder);
}