【问题标题】:How to reattach/rebind Events on Ajax loaded Content?如何在 Ajax 加载的内容上重新附加/重新绑定事件?
【发布时间】:2016-08-05 09:44:48
【问题描述】:

我的网站 添加到购物车 ** 是通过 ajax 完成的。现在我有一个按钮,可以通过页面上的 ajax 插入新产品。我的问题是新添加的产品**添加到购物车表单不适用于 ajax。

<ul>
  <li>
    <form action="add-to-cart.php?product_id=1">....</form>
  </li>
  <li>
    <form action="add-to-cart.php?product_id=2">....</form>
  </li>
<li>
    <form action="add-to-cart.php?product_id=3">....</form>
  </li>
<li>
    <form action="add-to-cart.php?product_id=4">....</form>
  </li>
<li>
    <form action="add-to-cart.php?product_id=5">....</form>
  </li>
</ul>
<button id="load-more">Load More Products</a>

我知道我可以像这样绑定事件

$(document).on("submit", 'form', function(event) { 
    //logic here
});

但我无权访问具有逻辑的 js 文件(可以说我无法编辑文件)。

所以我的问题是我可以在新加载的 ajax 内容上重新附加/重新绑定事件吗(具体而言,添加到购物车表单)。

编辑 现有addto cart js文件的代码

/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
define([
    'jquery',
    'mage/translate',
    'jquery/ui'
], function($, $t) {
    "use strict";

    $.widget('mage.catalogAddToCart', {

        options: {
            processStart: null,
            processStop: null,
            bindSubmit: true,
            minicartSelector: '[data-block="minicart"]',
            messagesSelector: '[data-placeholder="messages"]',
            productStatusSelector: '.stock.available',
            addToCartButtonSelector: '.action.tocart',
            addToCartButtonDisabledClass: 'disabled',
            addToCartButtonTextWhileAdding: '',
            addToCartButtonTextAdded: '',
            addToCartButtonTextDefault: ''
        },

        _create: function() {
            if (this.options.bindSubmit) {
                this._bindSubmit();
            }
        },

        _bindSubmit: function() {
            var self = this;
            this.element.on('submit', function(e) {
                e.preventDefault();
                self.submitForm($(this));
            });
        },

        isLoaderEnabled: function() {
            return this.options.processStart && this.options.processStop;
        },

        /**
         * Handler for the form 'submit' event
         *
         * @param {Object} form
         */
        submitForm: function (form) {
            var addToCartButton, self = this;

            if (form.has('input[type="file"]').length && form.find('input[type="file"]').val() !== '') {
                self.element.off('submit');
                // disable 'Add to Cart' button
                addToCartButton = $(form).find(this.options.addToCartButtonSelector);
                addToCartButton.prop('disabled', true);
                addToCartButton.addClass(this.options.addToCartButtonDisabledClass);
                form.submit();
            } else {
                self.ajaxSubmit(form);
            }
        },

        ajaxSubmit: function(form) {
            var self = this;
            $(self.options.minicartSelector).trigger('contentLoading');
            self.disableAddToCartButton(form);

            $.ajax({
                url: form.attr('action'),
                data: form.serialize(),
                type: 'post',
                dataType: 'json',
                beforeSend: function() {
                    if (self.isLoaderEnabled()) {
                        $('body').trigger(self.options.processStart);
                    }
                },
                success: function(res) {
                    if (self.isLoaderEnabled()) {
                        $('body').trigger(self.options.processStop);
                    }

                    if (res.backUrl) {
                        window.location = res.backUrl;
                        return;
                    }
                    if (res.messages) {
                        $(self.options.messagesSelector).html(res.messages);
                    }
                    if (res.minicart) {
                        $(self.options.minicartSelector).replaceWith(res.minicart);
                        $(self.options.minicartSelector).trigger('contentUpdated');
                    }
                    if (res.product && res.product.statusText) {
                        $(self.options.productStatusSelector)
                            .removeClass('available')
                            .addClass('unavailable')
                            .find('span')
                            .html(res.product.statusText);
                    }
                    self.enableAddToCartButton(form);
                }
            });
        },

        disableAddToCartButton: function(form) {
            var addToCartButtonTextWhileAdding = this.options.addToCartButtonTextWhileAdding || $t('Adding...');
            var addToCartButton = $(form).find(this.options.addToCartButtonSelector);
            addToCartButton.addClass(this.options.addToCartButtonDisabledClass);
            addToCartButton.find('span').text(addToCartButtonTextWhileAdding);
            addToCartButton.attr('title', addToCartButtonTextWhileAdding);
        },

        enableAddToCartButton: function(form) {
            var addToCartButtonTextAdded = this.options.addToCartButtonTextAdded || $t('Added');
            var self = this,
                addToCartButton = $(form).find(this.options.addToCartButtonSelector);

            addToCartButton.find('span').text(addToCartButtonTextAdded);
            addToCartButton.attr('title', addToCartButtonTextAdded);

            setTimeout(function() {
                var addToCartButtonTextDefault = self.options.addToCartButtonTextDefault || $t('Add to Cart');
                addToCartButton.removeClass(self.options.addToCartButtonDisabledClass);
                addToCartButton.find('span').text(addToCartButtonTextDefault);
                addToCartButton.attr('title', addToCartButtonTextDefault);
            }, 1000);
        }
    });

    return $.mage.catalogAddToCart;
});

【问题讨论】:

  • 我以为你已经回答了自己。因为 $(document).on("submit", 'form', function(event) { //这里的逻辑 });这就是重新绑定动态创建的事件的方式。

标签: javascript jquery ajax magento2


【解决方案1】:

谢谢大家,我已经找到解决办法了。我在 ajax 调用之后再次调用了 add to cart 方法,它起作用了。

$.ajax({
    dataType: 'html',
    type: 'GET',
    url:url,
    success: function(data){
        var data =  $($.parseHTML(data));
        var productList = data.find('.products.list').html(); 
        productWrapper.append(productList);
        $( "form" ).catalogAddToCart();  // this solved the problem
    },
});

【讨论】:

    【解决方案2】:

    尝试在 ajax 调用后加载该 javascript 文件 -

    $.getScript(src);
    

    【讨论】:

    • 文件是由require.js加载的,所以重新加载文件时出错
    • 不确定这是否可行,但请尝试再次加载 require.js。
    • 我认为这不是一个好主意。我已编辑问题以包含 addtocart js 文件。如果有帮助
    猜你喜欢
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2013-03-13
    • 2014-06-23
    相关资源
    最近更新 更多