jQuery 1.7:将事件快捷方式(例如 click())转换为 on()?
我刚刚发现 jQuery 1.7 引入了一个新方法,on()
。通过我的简短研究,我将其视为绑定事件的一种综合方式,而不是决定 bind()
、live()
和 delegate 中的哪一个()
使用。在我看来,这是一个非常好的补充,可以带来很多好处。但随后我不确定是否需要转换事件快捷方式,例如 click()
。根据官方文档,click()
的定义是仍然.bind('click', handler)
的快捷方式。我认为 jQuery 开发人员在 v1.7+ 中重新定义 click() 和其他事件快捷方式以使用 on() 更有意义,不是吗?
I just found out that jQuery 1.7 introduced a new method, on()
. With my brief study, I see it as a consolidated way to bind events, as opposed to decide which one of bind()
, live()
, and delegate()
to use. IMO, this is a really nice addition that offers numerous benefits. But then I am not sure if I need to convert event shortcuts, such as click()
. According to the official document, the definition of click()
is still the shortcut to .bind('click', handler)
. I thought it would make more sense for the jQuery developers to redefine click() and other event shortcuts in v1.7+ to use on(), no?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
jQuery 文档清楚地将
.click()
表示为.on("click")
的简写,因此我想如果您愿意,您可以替换所有以前的调用。on()
方法文档摘录:方法
.on()
实际上与.bind()
的作用相同,只不过您可以一次绑定多个事件,并选择一组实际引发此事件的儿童数量。我认为使用
on()
而不是click()
更有意义,除非您需要绑定多个事件或通过过滤子项做一些更棘手的事情。jQuery documentation is clearly presenting
.click()
as a shorthand of.on("click")
, so I guess you can replace all your previous calls, if you want.Extract of the
on()
method documentation:The method
.on()
actually does the same as.bind()
except that you can bind multiple events at once, and select a set of children that actually fire this event.I don't think it makes more sense to use
on()
instead ofclick()
unless you need to bind multiple events or do some more tricky stuff with filtering children.ghusse 是对的,无需将所有 .click() 快捷方式替换为 .on(),但您应该将 .live() 代码替换为 .on(),因为 .live() 被标记为已弃用并且可能以及 jQuery 1.8 中删除...讨论正在进行中。
其中
UPSELECTOR
要么与SELECTOR
相同(那么您可以省略.on()
的第二个参数),要么它代表一个(一组) DOM 树中较高的元素,即事件冒泡时将遍历的元素。这里常见的选择是document
或body
ghusse is right, there is no need to replace all of your .click() shortcuts with .on(), but you should replace your .live() code with .on() because .live() is marked as deprecated and might as well be removed with jQuery 1.8 ... discussion is ongoing.
Where
UPSELECTOR
is either the same asSELECTOR
(then you can omit the second parameter of.on()
) or it represents a (set of) element(s) higher in the DOM tree, i.e. element(s) that will be traversed when the event is bubbling. A common choice here would bedocument
orbody