jQuery的添加/删除数组中的项目 [英] jquery add / remove item from array

查看:220
本文介绍了jQuery的添加/删除数组中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个3-4个复选框,当用户选中该复选框时,我想将该复选框的值添加到数组中,如果他们取消选中我要从数组中删除该项目的复选框,这就是我到目前为止:

I have a checkboxs 3-4 of them, when the user checks the checkbox I want to add the value of the checkbox to the array, if they uncheck the box I want to remove the item from the array, this is what I got so far:

$('ul.dropdown-menu input[type=checkbox]').each(function () {
    $(this).change(function () {

        if ($(this).attr("id") == 'price') {
            if (this.checked) {
                priceArray.push($(this).val());
            }
            else {
                priceArray = jQuery.grep(priceArray, function (value) {
                    return value != $(this).val();
                });
            }
        }
    });
});

将值添加到数组的效果很好,但是删除项目会导致此错误:

Adding the value to the array works perfectly, however removing items results in this error:

Cannot read property 'toLowerCase' of undefined

在此行:

return value != $(this).val();

推荐答案

替换

priceArray = jQuery.grep(priceArray, function (value) {
    return value != $(this).val();
});

通过

val = $(this).val();
priceArray = jQuery.grep(priceArray, function (value) {
    return value != val;
});

不要忘记您在回调函数中的作用域.

Don't forget the scope where your are in the callback function.

这篇关于jQuery的添加/删除数组中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆