如何在jQuery Success回调中精准定位对应锚点标签更新内容?
解决方案
问题根源
- 重复ID违规:所有锚点共用同一个
id="upvote-comment-url",但HTML要求ID必须唯一,导致getElementById只能匹配第一个元素,无法定位当前按钮对应的锚点。 - DOM定位错误:
$this.prev()获取的是按钮前方的<div>容器,而非容器内的锚点标签,直接对容器执行.html()会覆盖整个容器内容,而非目标锚点的文本。
修改步骤
1. 修正HTML:替换重复ID为类名
把锚点的id改为class,保证每个评论区的锚点能被精准识别:
<div class="upvote-comment-count"> <a href="{% url 'Suggestions:suggestion_comment_upvotes' pk=reply.id %}" class="upvote-comment-url"> {{ reply.total_comment_upvotes }} </a> </div> <button type="button" class="button6" data-href="{% url 'Suggestions:suggestion_comment_like' reply.id %}">Like</button>
2. 修正AJAX中的DOM定位逻辑
在success回调里,先定位到按钮前方的容器,再找到容器内的目标锚点,最后更新其文本内容:
$(document).on("click", '.button6', function(e){ e.preventDefault(); const $this = $(this); // 缓存当前点击的按钮 $.ajax({ type: "POST", url: $this.data("href"), dataType: "json", headers: { "X-CSRFToken": "{{ csrf_token }}" // 用headers配置CSRF更简洁 }, success: function(response){ // 精准定位到当前按钮对应的锚点并更新数字 $this.prev('.upvote-comment-count') .find('.upvote-comment-url') .text(response['total_comment_upvotes']); }, }); return false; });
额外优化点
- 用
const声明$this,避免全局变量污染。 - 替换
beforeSend为headers配置CSRF Token,代码更简洁。 - 使用
.text()而非.html()更新内容,仅处理纯文本更安全。
内容的提问来源于stack exchange,提问作者Steve Smith
相关产品推荐
相关产品推荐

