html
<span id="count" style="margin-top: -5%;" class="likes_count">5 likes</span>
这是我的 JavaScript 代码
$(document).ready(function(){
// when the user clicks on like
$(document).on('click','.like',function(){
$('.like').addClass('animated bounceIn');
var postid = $(this).data('id');
var id = $(this).attr('data-likes');
$post = $(this);
$.ajax({
url: 'dashboard.php',
type: 'POST',
data: {
'liked': 1,
'postid': postid
},
success: function(response){
$post.parent().find('span.likes_count').text(id+1+"likes");
$post.addClass('hide');
$post.siblings().removeClass('hide');
}
});
});
我正在获取 id 变量中的类似数量,但不知道如何成功增加它,我在代码中尝试过,但不起作用,它在整数前面添加 1 有帮助
最佳答案
只需替换这个:
$post.parent().find('span.likes_count').text(id+1+"likes");
与:
$post.parent().find('span.likes_count').text((+id+1)+"likes");
问题在于 id
以及 "likes"
都是字符串,因此 Javascript 将 +
运算符解释为在字符串之间进行连接。 “一元加号”+id
将其转换为数字(您也可以使用 Number(id)
,有些人认为这更明确,但我个人认为很冗长),然后通过将 +id+1
放在括号中,可以确保在与 "likes"
进行字符串连接之前将其视为数字加法。
关于javascript - 如何增加按钮点击jquery的数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52905861/