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

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


当前回答

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

old:

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

new:

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

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

其他回答

您可以通过包含以下JavaScript代码来避免重构代码

jQuery.fn.extend({
    live: function (event, callback) {
       if (this.selector) {
            jQuery(document).on(event, this.selector, callback);
        }
        return this;
    }
});

jQuery >= 1.9 .live()的前向端口 避免重构JS对.live()的依赖 使用优化的DOM选择器上下文

/** 
 * Forward port jQuery.live()
 * Wrapper for newer jQuery.on()
 * Uses optimized selector context 
 * Only add if live() not already existing.
*/
if (typeof jQuery.fn.live == 'undefined' || !(jQuery.isFunction(jQuery.fn.live))) {
  jQuery.fn.extend({
      live: function (event, callback) {
         if (this.selector) {
              jQuery(document).on(event, this.selector, callback);
          }
      }
  });
}

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

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

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

bundle update jquery-rails

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

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

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

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

此外,它还指出:

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