jQuery中live()变更
开始的时候在jQuery.1.7.1中使用了.live()觉得很好用,特别是在绑定事件之后再加入的元素的事件绑定上很方便(第一次live之后以后添加的元素就不需要绑定啦)
后来jQuery更新到1.9.1,页面中的.live报错:"has no method live", 后来查了文档才知道在新版本中做了修改。
jQuery.1.8.1:
$("#liveID").live("click",function(){alert("live click");});
jQuery.1.9.1:
$(document).on("click","#liveID",function(){alert("live click");});
jQuery网站上这么说的:
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()
.
This method provides a means to attach delegated event handlers to the document
element of a page, which simplifies the use of event handlers when content is dynamically added to a page. See the discussion of direct versus delegated events in the.on()
method for more information.
改进后的使用建议:
1 $(selector).live(events, data, handler); // jQuery 1.3+
2 $(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
3 $(document).on(events, selector, data, handler); // jQuery 1.7+
示例:
1 $("a.offsite").live("click", function(){ alert("Goodbye!"); }); // jQuery 1.3+
2 $(document).delegate("a.offsite", "click", function(){ alert("Goodbye!"); }); // jQuery 1.4.3+
3 $(document).on("click", "a.offsite", function(){ alert("Goodbye!"); }); // jQuery 1.7+
PS:jQuery也不能随便更新升级的,要看看每次更新都有些什么变动,不然更新后系统就会有问题啦。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· 对象命名为何需要避免'-er'和'-or'后缀
· JDK 24 发布,新特性解读!
· Java24你发任你发,我用Java8
· C# 中比较实用的关键字,基础高频面试题!
· .NET Core奇技淫巧之WinForm使用Python.NET并打包