我最近将 jQuery 从 1.8 更新到 2.1。我突然发现.live()停止工作。
我收到错误TypeError: $(...).live is not a function。
有什么方法可以代替.live()吗?
我最近将 jQuery 从 1.8 更新到 2.1。我突然发现.live()停止工作。
我收到错误TypeError: $(...).live is not a function。
有什么方法可以代替.live()吗?
.live()已从 1.9 版开始删除。这意味着如果您从 1.8 版及更早版本升级,如果您不遵循下面的迁移指南,您会发现事情很糟糕。您不能简单地替换.live()为.on()!
对于快速/热补丁上线的站点,不只是替换关键字live用on,
因为参数是不同的!
.live(events, function)
应该映射到:
.on(eventType, selector, function)
(子)选择器非常重要!如果您出于任何原因不需要使用它,请将其设置为null.
前:
$('#mainmenu a').live('click', function)
之后,您将子元素 ( a)移动到.on()选择器:
$('#mainmenu').on('click', 'a', function)
前:
$('.myButton').live('click', function)
之后,您将元素 ( .myButton)移动到.on()选择器,并找到最近的父元素(最好带有 ID):
$('#parentElement').on('click', '.myButton', function)
如果您不知道将什么作为父项,请body始终有效:
$('body').on('click', '.myButton', function)
您可以通过包含以下 JavaScript 代码来避免重构您的代码
jQuery.fn.extend({
    live: function (event, callback) {
       if (this.selector) {
            jQuery(document).on(event, this.selector, callback);
        }
        return this;
    }
});
.live()jQuery >= 1.9 的转发端口避免重构 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);
          }
      }
  });
}
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()