我想知道是否有更好的方法来向数组添加/删除复选框值。遗憾的是我无法使用 ECMAScript 5 indexOf()
因为我需要支持 IE8/7。
这是一个有效的 jsfiddle 示例:http://jsfiddle.net/puyQr/
这个方法的作用是:
/**
* If a user clicks onto the checkbox, the value of the value attribute is
* only added to the array when the value not yet exists. However, if
* the value already exists, the value is removed.
*/
var values = [];
jQuery(':checkbox').on('click', function(){
var index = jQuery.inArray(this.value, values);
if(index === -1) {
values.push(this.value);
} else {
values.splice(index, 1);
}
});
最佳答案
从复选框获取值的另一种方法:
var values = jQuery(':checkbox:checked').map(function(){
return $(this).val();
}).get();
关于javascript - 优化Javascript方法来填充或清空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14280442/