javascript - Jquery 取消移位/取消设置数组项

标签 javascript jquery

我创建了一个简单的按钮,它将按钮的值添加到数组中,然后在再次单击时将其删除。

        var inviteList = [];

        $('.invite').click(function(event) {

            if($(this).hasClass('btn-success')){
                inviteList.unshift($(this).data('client'));
                $(this).removeClass("btn-success");
                console.log('removing');
            }else{
                inviteList.push($(this).data('client'));
                $(this).addClass("btn-success");
                console.log(inviteList);
            }

        });

问题是项目没有被删除,但它们正在被触发。

console.log

[22] 
removing videos
[22, 22, 22] 
removing videos:311
[22, 22, 22, 22, 22] 
removing videos
[22, 22, 22, 22, 22, 22, 22] 
removing videos

有什么想法吗,我的方法有误吗?

最佳答案

您需要找到该项目的索引,然后将其删除

var inviteList = [];

$('.invite').click(function (event) {

    if ($(this).hasClass('btn-success')) {
        var index = inviteList.indexOf($(this).data('client'));
        inviteList.splice(index, 1);
        $(this).removeClass("btn-success");
        console.log('removing');

    } else {
        inviteList.push($(this).data('client'));
        $(this).addClass("btn-success");
        console.log(inviteList);
    }

});

Array.unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

关于javascript - Jquery 取消移位/取消设置数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26359092/

相关文章:

javascript - 需要帮助添加选项以使用 javascript 进行选择

javascript - 数组分组和计数

javascript - 如何使用 JQuery 一次更新数组变量上的多个复选框值

jquery - 创建看起来更严重的 jQuery 错误对话框?

javascript - 缩进jqgrid组的子元素

javascript - 如何处理缓慢的 Ajax 请求/连接缓慢的人

jquery - jQuery Mobile 中的自定义按钮

javascript - 如何在页面顶部将多个div设置为 “position: fixed and top:0”

php - 这个网站 (allaboutrajni) 如何仅在您离线时工作? (断开互联网连接)

javascript - AngularJS - 如何访问嵌套 ng-repeat 中的数组