我创建了一个简单的按钮,它将按钮的值添加到数组中,然后在再次单击时将其删除。
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);
}
});
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/