语境
我正在尝试实现一项功能,以便当用户单击表中的复选框时,该复选框的属性value
和data-title
应该存储在名为selected
新键-值对数组元素的JS对象文字中。
如果用户再次单击同一复选框,则应删除相应的数组元素。
问题
第一次单击复选框时,selected
将按预期在对象中创建一个数组。
但是,再次单击同一复选框时,不是删除相应的数组,而是添加了一个新的(重复的)数组。
代码
var selected = {items:[]};
$('#table').on('click', 'input[type="checkbox"]', function() {
var found = false;
$.each(selected.items, function(i, val) {
if (val.key == $(this).attr("value")) {
selected.items.splice(i ,1);
found = true;
return false; //step out of each()
}
});
if (found == false) {
selected.items.push({key: $(this).attr("value"), value: $(this).attr("data-title")});
}
console.log(selected);
});
你有错误的上下文this
中each
。它不再是点击处理程序中的元素
尝试
$('#table').on('click', 'input[type="checkbox"]', function() {
var found = false;
var value = $(this).val();// store value from `this` before entering `each`
$.each(selected.items, function(i, val) {
if (val.key == value) {
selected.items.splice(i ,1);
found = true;
return false; //step out of each()
}
});
....
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句