You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 08:25:33