我已经创建了一个简单的按钮,它将按钮的值添加到数组中,如果再次单击,则将其移除。
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有什么想法吗,我是不是搞错了?
发布于 2014-10-14 10:57:27
您需要找到该项的索引,然后删除它。
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);
}
});unshift()方法将一个或多个元素添加到数组的开头,并返回数组的新长度。
https://stackoverflow.com/questions/26359092
复制相似问题