【发布时间】:2018-01-21 13:04:08
【问题描述】:
我有一个具有整数计数的元素。
<span class="likes-count"> 2 </span>
并且一个 div 在点击时必须切换值的增量和减量。
<div class="liked"></div>
问题:
我在$('.liked').clicked 上调用了一个函数,它增加了值并将类更改为.notliked
另一个 onclick 函数会减少该值,但它不能正常工作。
请查看我的代码。我想这不是最好的方法。
这是我的演示代码。
$(document).ready(function() {
$(".notliked").click(function() {
var $this = $(this);
$this.removeClass('notliked');
$this.addClass('liked')
$count = $('.likes-count');
$count.html((parseInt($count.html(),10) || 0) + 1);
});
$(".liked").click(function() {
var $this = $(this);
$this.removeClass('liked');
$this.addClass('notliked');
$count = $('.likes-count');
$count.html((parseInt($count.html(),10) || 0) - 1);
});
});
.heart {
color: #fff;
height:50px;
cursor:pointer;
width:50px;
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<span class="likes-count"> 2 </span>
<div class="liked heart">Click</div>
【问题讨论】:
-
可能想要使用
.toggleClass()来代替 - api.jquery.com/toggleclass -
我试过了。它对我的问题不起作用。
标签: javascript jquery html