jQuery on()方法不会像live()那样绑定事件 [英] jQuery on() method does not bind events like live() did
问题描述
如 http://api.jquery.com/live/
中所述:
从jQuery 1.7开始,不推荐使用.live()方法.使用.on()附加事件处理程序.
对. 因此代替
$('.dynamicallyCreatedElement').live('click', function(){
console.log('click');
});
我应该使用:
$('.dynamicallyCreatedElement').on('click', function(){
console.log('click');
});
但是,它不会将事件绑定到on()
调用之后创建的元素.那么live()
方法真的更好吗?
我想念什么吗?
要使用 on
与> live
的工作方式相同,您需要像这样使用它:>
$(document).on("click", ".dynamicallyCreatedElement", function() {
console.log('click');
});
因此,您将on
处理程序绑定到document
本身(或者实际上是新元素将出现"的容器元素-感谢@ devnull69的阐明),然后将其传递给事件类型和选择器.
在 live
文档页面的中途,您会找到几个示例./p>
As described on http://api.jquery.com/live/
:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
Right. So instead of
$('.dynamicallyCreatedElement').live('click', function(){
console.log('click');
});
I should use:
$('.dynamicallyCreatedElement').on('click', function(){
console.log('click');
});
However it does not bind event to elements created after on()
calling. So is it really better live()
method ?
Am I missing something ?
To use on
in the same manner as live
used to work you need to use it like:
$(document).on("click", ".dynamicallyCreatedElement", function() {
console.log('click');
});
So you bind the on
handler to the document
itself (or, actually, the container element where the new wlements will be "appearing" -- Thanks to @devnull69 for the clarification), then pass it an event type and the selector.
You'll find a couple of examples halfway through the live
documentation page.
这篇关于jQuery on()方法不会像live()那样绑定事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!