当我选择按钮时,console.log
上出现值,使用数组可以正常工作。我也想在取消选择按钮时从控制台中删除值。
var totalWishlist = [];
$('.btn').click(function() {
$(this).toggleClass('active');
totalWishlist.push($(this).data('pid'));
console.log(totalWishlist.join(', '));
});
.btn{background:gray; color:#fff; padding:10px; border-radius:15px; margin-bottom:10px; display:inline-block;}
.active{background:red; color:#fff; padding:10px; border-radius:15px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn" data-pid="1">btton 1</div>
<div class="btn" data-pid="2">btton 2</div>
<div class="btn" data-pid="3">btton 3</div>
<div class="btn" data-pid="4">btton 4</div>
答案 0 :(得分:1)
最简单的方法是在每个事件处理程序中构建数组,而不是在单击新元素/删除一个新元素时手动对其进行维护。为此,您可以像这样使用map()
:
$('.btn').click(function() {
$(this).toggleClass('active');
var totalWishlist = $('.btn.active').map(function() {
return $(this).data('pid');
}).get();
console.log(totalWishlist.join(', '));
});
.btn {
background: gray;
color: #fff;
padding: 10px;
border-radius: 15px;
margin-bottom: 10px;
display: inline-block;
}
.active {
background: red;
color: #fff;
padding: 10px;
border-radius: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn" data-pid="1">btton 1</div>
<div class="btn" data-pid="2">btton 2</div>
<div class="btn" data-pid="3">btton 3</div>
<div class="btn" data-pid="4">btton 4</div>
答案 1 :(得分:1)
您可以检查类的存在,以便可以添加/删除该项目:
-threads 1
var totalWishlist = [];
$('.btn').click(function() {
$(this).toggleClass('active');
if($(this).hasClass('active'))
totalWishlist.push($(this).data('pid'));
else
totalWishlist = totalWishlist.filter(i => i!= $(this).data('pid'));
console.log(totalWishlist.join(', '));
});
.btn{background:gray; color:#fff; padding:10px; border-radius:15px; margin-bottom:10px; display:inline-block;}
.active{background:red; color:#fff; padding:10px; border-radius:15px;}