如何在JS中实现与按钮分离的评分总和计数器点击更新功能
核心问题排查
原有代码存在以下几处逻辑错误,直接导致功能失效:
- 选择器不匹配:实际按钮类名为
btn-like-up/btn-like-down,原有代码写的.btn-like.up无法匹配到任何元素 - 事件类型错误:按钮点击需使用
click事件,submit是表单专属的提交事件,无法绑定给普通按钮 - 变量赋值错误:
$(this).data('id')取到的是帖子ID字符串,不是DOM对象,后续调用.data()、.find()方法都会直接报错 - 计数器定位错误:没有匹配当前帖子对应的独立计数器,会出现多帖评分互相干扰的问题
修正方案
以下代码不需要修改原有HTML结构,自动适配10篇帖子的使用场景,符合「仅使用按钮之间的独立计数器」的需求:
// 绑定所有投票按钮的点击事件,后续新增帖子也能自动适配,不需要重复写逻辑 $(document).on('click', '.btn-like-up, .btn-like-down', function(e) { e.preventDefault(); const $currentBtn = $(this); // 直接从当前点击的按钮取所需参数 const postId = $currentBtn.data('id'); const postType = $currentBtn.data('type'); const postAction = $currentBtn.data('action'); // 精准定位对应计数器:上按钮的下一个兄弟元素就是计数器,下按钮的上一个兄弟元素就是计数器 const $totalRating = $currentBtn.hasClass('btn-like-up') ? $currentBtn.next('[data-count="total_rating"]') : $currentBtn.prev('[data-count="total_rating"]'); $.ajax({ type: 'POST', url: `/system/${postType}/${postId}/${postAction}/`, data: { 'post_id': postId, 'csrfmiddlewaretoken': csrftoken }, success: function(response) { $totalRating.text(response.total_rating); }, error: function(error) { console.log(error); }, }) })
可选维护优化:如果后续可能调整DOM结构,建议给每个帖子的投票区域套一层
class="post-rating"的父容器,计数器定位就可以改成更稳定的$currentBtn.closest('.post-rating').find('[data-count="total_rating"]'),不受元素顺序调整影响。
内容的提问来源于stack exchange,提问作者Razilator
相关产品推荐
相关产品推荐

