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

AJAX加载分页内容后绑定的jQuery点击事件失效该如何解决?

AJAX加载页面内容后jQuery代码失效解决方案

你当前使用的直接绑定事件的写法,只会在document.ready执行时给已经存在于DOM中的.variable-item.image-variable-item元素绑定点击事件。AJAX动态插入的新分页商品元素不会被自动绑定,因此点击没有响应,使用事件委托即可解决该问题。

修正后的完整代码如下:

(function($){
    $(document).ready(function(){
        // 将事件委托到永久存在的根节点,动态插入的元素也能触发对应事件
        $(document).on("click", ".variable-item.image-variable-item", function(){
            if($(this).parents('.jet-woo-product-button').length){
                let btn = $(this).parents('.jet-woo-product-button').find('.add_to_cart_button');
                if(btn.length){
                    // 调整绑定顺序,避免先触发点击再绑定标记的逻辑漏洞,增加off避免重复绑定
                    btn.off('click.mark').on('click.mark', function(){
                        btn.data('clicked', true);
                    });
                    btn.click();
                    setTimeout(function(){
                        if(btn.data('clicked') != true){
                            btn.click();
                        }
                        btn.data('clicked', false);
                    }, 500);
                }
            } else if($(this).parents('.variations_form').find('.single_add_to_cart_button').length){
                let btn = $(this).parents('.variations_form').find('.single_add_to_cart_button');
                if(btn.length){
                    setTimeout(function(){
                        btn.click(); 
                    }, 500);
                }
            }
        });
    });
})(jQuery);
  • 优先将事件委托的宿主替换为页面中永久存在、且更靠近商品列表的父容器(比如商品列表的外层固定容器),可降低事件冒泡带来的性能损耗
  • 该写法无需在AJAX请求成功的回调中重复绑定事件,一次绑定即可适配所有动态插入的符合选择器规则的元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 10:18:02