jQuery 1.9 .live() is not a function
我最近将jQuery从1.8更新到了2.1。 我突然发现
我收到错误
有什么方法可以代替
jQuery
这意味着,如果您要从1.8版或更早版本进行升级,则如果不遵循以下迁移指南,将会发现事情中断了。您不能仅将
开始搜索并替换之前,请先阅读以下内容:
要在实时站点上进行快速/热修复,请勿仅将关键字
1 | .live(events, function) |
应该映射到:
1 | .on(eventType, selector, function) |
(子)选择器非常重要!如果由于任何原因不需要使用此功能,请将其设置为
迁移示例1:
之前:
1 | $('#mainmenu a').live('click', function) |
之后,将子元素(
1 | $('#mainmenu').on('click', 'a', function) |
迁移示例2:
之前:
1 | $('.myButton').live('click', function) |
之后,将元素(
1 | $('#parentElement').on('click', '.myButton', function) |
如果您不知道要作为父项放置什么,则
1 | $('body').on('click', '.myButton', function) |
也可以看看:
- jQuery-如何使用" on()"方法代替" live()"?
- jQuery 1.9迁移指南
您可以通过包含以下JavaScript代码来避免重构代码
1 2 3 4 5 6 7 8 | jQuery.fn.extend({ live: function (event, callback) { if (this.selector) { jQuery(document).on(event, this.selector, callback); } return this; } }); |
jQuery> = 1.9的
避免重构
使用优化的DOM选择器上下文
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | /** * 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文档列出了
version deprecated: 1.7, removed: 1.9
此外,它指出:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live()
.live()已弃用,现已从jQuery 1.9中删除。
您应该使用.on()
一个非常简单的修复程序,无需更改代码,只需添加jquery迁移脚本,请在此处下载
https://github.com/jquery/jquery-migrate/
它提供了不建议使用的jQuery,但需要一些功能,例如"实时","浏览器"等
.live在1.9中已删除,请参阅升级指南:http://jquery.com/upgrade-guide/1.9/#live-removed
如果没有必要,我倾向于不使用.on()语法。例如,您可以像这样轻松迁移:
旧:
1 | $('.myButton').live('click', function); |
新:
1 | $('.myButton').click(function) |
以下是有效事件处理程序的列表:https://api.jquery.com/category/forms/
如果您碰巧正在使用Ruby on Rails的jQuery gem
1 | gem 'jquery-rails', '~> 2.1', '= 2.1.3' |
那么您可以使用以下命令进行更新:
1 | bundle update jquery-rails |
希望对其他面临类似问题的人有所帮助。