jquery – 我应该使用.on()或.click()来附加事件处理程序吗?

假设我只想将一个简单的点击处理程序附加到一个元素,我总是这样做:

$("#mydiv").click(function() { ... });

看看JQuery文档,似乎.on()是附加事件处理程序并替换.bind(),. delegate()和.live()的“推荐”方式:

As of jQuery 1.7,the .on() method provides all functionality required
for attaching event handlers. For help in converting from older jQuery
event methods,see .bind(),.delegate(),and .live().

.click()的文档中,它说:

This method is a shortcut for .bind(‘click’,handler) in the first two variations,and .trigger(‘click’) in the third.

所以这意味着.click()正在使用.bind(),它将被弃用并替换为.on(),对吧?或者暗示.click()会坚持下去,但它会在某些时候成为.on(“点击”)的捷径?

基本上,我的问题是这个…今天编写JQuery代码时,我应该使用:

Variant 1: $("#mydiv").click(function() { ... });

要么:

Variant 2: $("#mydiv").on("click",function() { ... });

最佳答案
就个人而言,我会使用on()来处理来自jQuery 1.7的所有事件绑定.

这意味着动态添加的元素和页面加载的元素之间没有歧义.

另外,正如您所述,click()(和其他事件快捷方式)将转换为on(“event”,function(){…});无论如何,通过jQuery,它可以节省一个步骤 – 当然,这不会产生明显的差异.

最后,在我看来,(“点击”)读起来更好.

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...