如何将我的所有live()函数替换为on()函数

时间:2013-05-06 06:27:56

标签: javascript jquery html web-applications client

由于Jquery 1.9已弃用live()函数,因此我必须将其更改为替代on()

一切似乎都很好。

在我的项目中,我使用了近100个live()个函数。如果我去每个地方并改为on(),它应该会很好用。

是否有任何有效方式或script使用on()功能,我现在使用live()

这会节省我很多时间。

请同时推荐其他任何选项。

感谢。

2 个答案:

答案 0 :(得分:2)

您可以尝试使用jQuery migrate,它用于检测和恢复已在jQuery中弃用并从1.9版开始删除的API或功能。

答案 1 :(得分:1)

可能你可以调整一下这一点!

只需使用您自己的.live()函数扩展jquery,内部指向.on()

    (function(jQuery) {
        // Store a reference to the original remove method.
        var originalOnMethod = jQuery.fn.on;

        // Define overriding method.
        jQuery.fn.live = function() {
            // event is bind for the elements added dynamically as well. 
            if(typeof arguments[0] == "string" && typeof arguments[1] == "function"){
                $(document).on(arguments[0], this.selector, arguments[1]);
            }else{//applied when proper live syntax is not followed and event will not fire for dynamically added elements  
                originalRemoveMethod.apply( this, arguments );
            }

        }
    })(jQuery);

我刚刚创建了这个功能并进行了测试,它可以工作,但你永远不知道它在哪里打破。如果它需要任何凝结,请回复。谢谢! : - )