jQuery on()方法不会像live()那样绑定事件 [英] jQuery on() method does not bind events like live() did

查看:56
本文介绍了jQuery on()方法不会像live()那样绑定事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆