【问题标题】:on click event won't fire after AJAX filter manipulates the DOM在 AJAX 过滤器操作 DOM 后,点击事件不会触发
【发布时间】:2015-03-16 09:10:58
【问题描述】:

我正在开发一个具有 AJAX 过滤器的电子商务网站,该过滤器根据每个产品属性操作 dom。

我正在编写另一个 AJAX 调用,以便在点击时为每个产品提取更多产品属性。

Here is the link to the dev site

这是我的 AJAX 调用

$('.each-product').on('click', function (e) {

    /** Prevent Default Behaviour */
    e.preventDefault();

    /** Get Post ID */
    var post_id = $(this).attr('id');
    var response_class = '.' + post_id + '-ajax-response';


    /** Ajax Call */
    jQuery.ajax({
        type: 'POST',
        url: ajaxurl,
        data: { action: 'product_extra_info', id: post_id },
        beforeSend: function () {
            $(response_class).show().html("Loading...");
        },
        success: function (data) {
            $(response_class).show().html(data);
            //alert(data);
        }

    });
    return false;
});

【问题讨论】:

  • 您应该将点击事件绑定到那些动态创建的 DOM 元素。 (懒加载创建的)
  • 控制台中出现任何错误?
  • 使用事件委托。去阅读 jQuery 的 .on 上的文档,看看它是如何工作的。
  • @vrej 请发布您用于定义在 ajax 过滤器后调用的单击函数的 jQuery 函数代码..

标签: php jquery ajax wordpress woocommerce


【解决方案1】:

请参阅.on 事件委托。使用click,您无法绑定到动态添加到 DOM 的内容。将您的代码切换为使用 on 如下所示:

$('.products').on('click', '.each-product', function (e) {

    /** Prevent Default Behaviour */
    e.preventDefault();

    /** Get Post ID */
    var post_id = $(this).attr('id');
    var response_class = '.' + post_id + '-ajax-response';


    /** Ajax Call */
    jQuery.ajax({
        type: 'POST',
        url: ajaxurl,
        data: { action: 'product_extra_info', id: post_id },
        beforeSend: function () {
            $(response_class).show().html("Loading...");
        },
        success: function (data) {
            $(response_class).show().html(data);
            //alert(data);
        }

    });
    return false;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-18
    • 2020-12-27
    • 2014-09-25
    • 2013-05-19
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多