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

jQuery中$.post的.done()回调内无法为元素执行addClass操作如何解决

问题原因

  • this指向错误:$.post的回调函数默认this指向AJAX请求的配置对象,而非触发blur事件的input元素,回调内$(this)无法选中目标输入框。
  • 判断条件不匹配:PHP接口返回的是字符串updated,但JS中判断逻辑写的是data == "update",字符串不匹配导致加类逻辑永远不会触发。
  • 冗余DOM查询:原代码中$(this).closest('td').find('input.autosave2')属于多余操作,你要操作的就是触发事件的input本身,不需要再向上查找父级后反向查询。

修复代码

方案1(兼容性最优):提前缓存目标元素

在blur事件触发时先把当前元素存为变量,回调内直接调用即可:

$(".autosave2").on('blur',function(){
    // 提前缓存当前触发事件的输入框
    const $target = $(this);
    const i_name = $target.attr('name');
    const i_val = $target.val();
    const i_oval = $target.data('oval');

    $.post("settings_price_limit.php", {name:i_name, val:i_val, oval:i_oval, mode:'default'}, function(data) {
        console.log(data);    
        // 修正判断条件和接口返回对齐,加trim避免返回带多余空白字符
        if(data.trim() === "updated"){
            $target.addClass('is-valid');
        }
    });
});

方案2(ES6+环境适用):箭头函数继承外层this

箭头函数不会创建自己的this,会继承外层作用域的this指向:

$(".autosave2").on('blur',function(){
    const i_name = $(this).attr('name');
    const i_val = $(this).val();
    const i_oval = $(this).data('oval');

    // 回调改为箭头函数
    $.post("settings_price_limit.php", {name:i_name, val:i_val, oval:i_oval, mode:'default'}, (data) => {
        console.log(data);    
        if(data.trim() === "updated"){
            $(this).addClass('is-valid');
        }
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 20:39:03