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

如何在jQuery的post请求done回调中获取并操作被点击的DOM元素

问题原因

$.post 的 done 回调中 this 指向发生了改变,默认情况下回调的 this 指向 jQuery 异步请求的 jqXHR 对象,而非你点击的 .status-item 元素,所以 $(this) 无法匹配到目标 DOM,操作自然没有效果。

解决方案

方案1:提前缓存DOM引用

在触发点击事件后、发送请求前先将点击元素的引用存储下来,回调中直接使用缓存的变量操作即可,兼容性最好:

$(".status-item").click(function(){
  // 提前缓存当前点击的元素
  const $currentItem = $(this);
  $.post( "/api/orderstatus/{{$order->id}}", { status_id: 1 })
  .done(function( data ) {
    // 直接用缓存的元素操作DOM
    $currentItem.parent().parent().addClass('noticeme');
    // 后续修改按钮文本也可以基于该元素向上查找对应节点
  });
});

方案2:使用ES6箭头函数

箭头函数不会绑定独立的this,会继承外层作用域的this指向,不用额外缓存变量:

$(".status-item").click(function(){
  $.post( "/api/orderstatus/{{$order->id}}", { status_id: 1 })
  // 回调改为箭头函数
  .done((data) => {
    $(this).parent().parent().addClass('noticeme');
  });
});

方案3:显式指定回调的context

通过context参数手动指定回调函数的this指向:

$(".status-item").click(function(){
  $.post({
    url: "/api/orderstatus/{{$order->id}}",
    data: { status_id: 1 },
    context: this // 指定回调的this为当前点击的元素
  })
  .done(function( data ) {
    $(this).parent().parent().addClass('noticeme');
  });
});

优化建议

你找上层按钮组的逻辑可以替换为 closest('.btn-group'),不用连续写parent(),DOM结构有小调整时也不会失效,比如:
$currentItem.closest('.btn-group').addClass('noticeme')

内容的提问来源于stack exchange,提问作者Dylan Glockler

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:36:03