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

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


当前回答

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

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

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

bundle update jquery-rails

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

其他回答

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

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);
          }
      }
  });
}

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

old:

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

new:

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

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

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

一个非常简单的修复,不需要改变你的代码,只需要添加jquery迁移脚本,下载这里 https://github.com/jquery/jquery-migrate/

它提供了jquery弃用但需要的功能,如“live”,“浏览器”等