2015-09-02 80 views
0

我有一系列checkboxs的和變化的事件,像這樣:的jQuery的檢查,添加或更新數組對象項目

$(".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); 
    } 

這一點,我可以將項目添加到數組,但我的問題我將如何更新一個項目?我只想更新如果選中複選框。

回答

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); 
}); 
+0

** [小提琴這裏(https://jsfiddle.net/Guruprasad_Rao/1Lw5y2c7 /)** .. :) –

+0

這很好,但不是我想要的。 – user979331

+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); 
} 
相關問題