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

使用jQuery closest()配合Ajax注入HTML时功能失效问题求解

问题根本原因

该问题由AJAX回调函数的this指向变化导致:

  • 点击事件回调的this默认指向被点击的.show-content按钮元素,因此$(this).closest('li')可正常定位对应列表项。
  • jQuery AJAX的done()回调默认将this指向AJAX请求对应的jqXHR对象,不再是原按钮元素,$(this).closest('li')无法匹配到任何DOM节点,后续相关操作全部失效。
解决方案

以下三种为常用修复方案:

方案1:提前缓存this指向

在发起AJAX请求前将按钮的this存储到自定义变量中,回调内使用该变量替代this即可。

(function($) {
    $(document).ready(function() {
        $('.show-content').click(function() {
            // 缓存当前点击按钮的指向
            const $currentBtn = $(this);
            var post_id = $currentBtn.closest('article').attr('data-post-id');
            $currentBtn.closest('li').find('.content').prepend('<div class="loader">Loading...</div>'); 
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    'action': 'load_loop_content',
                    'post_id': post_id
                }
            }).done(function(response) {
                // 直接使用缓存的按钮对象操作
                $currentBtn.hide();
                $currentBtn.closest('li').find('.loader').hide();
                $currentBtn.closest('li').find('.content').html(response);
            });
        });
    });
})(jQuery);

方案2:通过AJAX的context参数指定回调上下文

在$.ajax配置中添加context参数,手动指定回调的this指向为当前点击的按钮。

$.ajax({
    url: ajaxurl,
    type: 'POST',
    // 指定回调上下文为当前点击按钮
    context: this,
    data: {
        'action': 'load_loop_content',
        'post_id': post_id
    }
}).done(function(response) {
    // 此处this与点击事件回调的this指向一致,可直接使用
    $(this).hide();
    $(this).closest('li').find('.loader').hide();
    $(this).closest('li').find('.content').html(response);
});

方案3:使用ES6箭头函数(需环境支持ES6+语法)

箭头函数不会生成独立的this作用域,会继承外层作用域的this指向,将done回调改为箭头函数即可直接使用外层的this。

.done((response) => {
    $(this).hide();
    $(this).closest('li').find('.loader').hide();
    $(this).closest('li').find('.content').html(response);
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:24:02