ajax之后的reinit功能

reinit function after ajax

本文关键字:功能 reinit 之后 ajax      更新时间:2023-09-26

我正在尝试重写一些脚本。这个脚本从数据属性中获取一些数据,并用它们重建块。一切都很好,但我需要通过AJAX来完成。这里是我修改后的脚本:

(function($){
jQuery.fn.someItem = function()
{
    var make = function() {
        var _$this = $(this);
        var $thumb = _$this.find('.thumb');
        function init()
        {
            $thumb.on('click', function()
            {
                if (!$(this).hasClass('active')) setNewActiveItem($(this));
                return false;
            });
        }
        function setNewActiveItem($newItem)
        {
            $.ajax({
                url: '/ajax-item?id=' + $newItem.data('id'),
                type: 'GET',
                success: function(response)
                {
                    _$this.replaceWith(response);
                    **init();**
                }
            });
        }
        init();
    };
    return this.each(make);
};
})(jQuery);

一切都很好,但在Ajax调用和块被替换后,我不能再在修改后的块中应用Ajax调用。我想我需要在"replaceWith()"之后重新命名"init()"函数,但如何做到呢?谢谢你的帮助。

将单击事件附加到.thumb元素时,需要在init()中使用委托的事件处理程序。试试这个:
var make = function() {
    var _$this = $(this);
    function init() {
        _$this.on('click', '.thumb', function() {
            if (!$(this).hasClass('active')) 
                setNewActiveItem($(this));
            return false;
        });
    }
    function setNewActiveItem($newItem) {
        $.ajax({
            url: '/ajax-item?id=' + $newItem.data('id'),
            type: 'GET',
            success: function(response) {
                _$this.replaceWith(response);
            }
        });
    }
    init();
};

这是通过将点击处理程序分配给父元素并在点击事件在DOM中冒泡时检查点击事件来实现的。这意味着您可以在任何时候附加任何.thumb元素,而不必重新分配任何新的单击处理程序,因为在父级上定义的处理程序将包罗万象。