【发布时间】:2017-01-10 12:54:18
【问题描述】:
我正在尝试使用 jQuery 排列一个复选框数组。我已经设法将值按顺序添加到数组中并删除正确的值,但是对于我的一生,我无法让它用新选择的值替换删除的值。目前它只是将新值添加到数组的末尾。
到目前为止,这是我的代码:
var array = [];
$('input[type="checkbox"]').click(function () {
if ($(this).attr('checked')) {
// Add the new element if checked:
array.push($(this).attr('value'));
$('#ff_elem512').val(array);
}
else {
// Remove the element if unchecked:
for (var i = 0; i < array.length; i++) {
if (array[i] == $(this).attr('value')) {
array.splice(i, 1);
$('#ff_elem512').val(array);
}
}
}
console.log(array);
});
提前致谢
【问题讨论】:
-
你的 html 是什么样的? $('#ff_elem512') 是什么?
-
您是否尝试将 $(this).attr('checked') 替换为 $(this).prop('checked')?
-
@Winter $('#ff_elem512') 是我发送数组的输入
-
@SylvainB 不,我现在没有生病尝试 - 尝试代码工作,因为它没有替换值
标签: javascript jquery arrays checkbox