我最近将jQuery从1.8更新到2.1。我突然发现.live()停止工作。 我得到错误TypeError: $(…)。Live不是一个函数。

是否有任何方法可以用来代替.live()?


当前回答

当我将得到这个错误在我的网站。它将停止一些功能 在我的网站上,经过研究,我找到了这个问题的解决方案,

$colorpicker_inputs.live('focus', function(e) {
    jQuery(this).next('.farb-popup').show();
    jQuery(this).parents('li').css( {
        position : 'relative',
        zIndex : '9999'
    })
    jQuery('#tabber').css( {
        overflow : 'visible'
    });
});

$colorpicker_inputs.live('blur', function(e) {
    jQuery(this).next('.farb-popup').hide();
    jQuery(this).parents('li').css( {
        zIndex : '0'
    })
});

应该替换'live'到'on'检查下面

    $colorpicker_inputs.on('focus', function(e) {
    jQuery(this).next('.farb-popup').show();
    jQuery(this).parents('li').css( {
        position : 'relative',
        zIndex : '9999'
    })
    jQuery('#tabber').css( {
        overflow : 'visible'
    });
});

$colorpicker_inputs.on('blur', function(e) {
    jQuery(this).next('.farb-popup').hide();
    jQuery(this).parents('li').css( {
        zIndex : '0'
    })
});

下面是一个更基本的例子:

.live(event, selector, function) 

改为:

.on(event, selector, function)

其他回答

jQuery API文档列出live()在1.7版已弃用,在1.9版已移除:link。

已弃用版本:1.7,已移除:1.9

此外,它还指出:

从jQuery 1.7开始,.live()方法已弃用。使用.on()附加事件处理程序。老版本jQuery的用户应该优先使用.delegate()而不是.live()

.live()已弃用,现已从jQuery 1.9中移除 你应该使用.on()

如果你碰巧正在使用Ruby on Rails的jQuery gem jQuery - Rails,由于某种原因你不能重构你的遗留代码,最后一个仍然支持的版本是2.1.3,你可以在你的Gemfile上使用下面的语法来锁定它:

gem 'jquery-rails', '~> 2.1', '= 2.1.3'

然后可以使用以下命令进行更新:

bundle update jquery-rails

我希望能帮助其他面临类似问题的人。

如果没有必要,我倾向于不使用.on()语法。例如,你可以像这样更容易地迁移:

old:

$('.myButton').live('click', function);

new:

$('.myButton').click(function)

下面是有效事件处理程序的列表:https://api.jquery.com/category/forms/

.live在1.9中被移除,请查看升级指南:http://jquery.com/upgrade-guide/1.9/#live-removed