.live()vs .on()方法 [英] .live() vs .on() method

查看:181
本文介绍了.live()vs .on()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个项目,其中当我继续按下最小/加号按钮,而没有用 .live()方法悬停图片,功能工作。在 .on()方法的函数不起作用。

I'm working on a project, in which when I keep pressing on the min/plus button without hovering off the picture with the .live() method, the function works. In the case of .on() method the function does not work.

如何解决这个问题,因此它也适用于 .on()方法?

How can I fix this issue, so it works for .on() method as well?

这里是一个例子我的参考(我修复了这个例子中的错误,但我使用的是 .on 方法错误。)

Here is an example of what I’m referring too (I fixed the error in this example, but I was using the .on method wrong).

推荐答案

替换 .live() $(document).on() ,当然...例如:

You're not using it correctly. The replacement for .live() is $(document).on() with the event and handler being passed in, of course... for example:

$(document).on('click', '#myElement', function() { 
  //... some function ...
});

值得一提的是 .on()过来, .live()已经被认为是一种低效的方式来处理这种绑定。 .delegate()被推荐,现在 .on()(使用委托语法)。

It's worth mentioning that before .on() ever came around, .live() was already considered an inefficient way to handle this kind of binding. .delegate() was recommended instead, and now .on() (using the delegator syntax).

或者作为一个例子:代替文档是监听器(这是 .live()你应该选择不会被DOM操作破坏的最近的祖先。我真的发现jsdo.it有点笨重使用,所以我没有具体的元素,但例如,给定的结构:

Or as an example: instead of the document being the listener (which is what .live() used to do), you should pick the nearest ancestor that does not get destroyed with DOM manipulations. I honestly find the "jsdo.it" a bit clunky to use so I don't have the specific element in mind, but for example, given the structure:

<div id="ajax_container">
 <button id="do_something">Clicky!</button>
 <p>Some dynamically-loaded content</p>
</div>

ajax_container 的内容被Ajax调用(不需要显示该部分的代码),绑定该按钮的点击事件的非销毁侦听器(容器div)将如下所示:

Where the contents of ajax_container are replaced by an Ajax call (no need to show the code for that part), binding a non-destroyed listener (the container div) for that button's click event would look like:

$('#ajax_container').on('click', '#do_something', function() {
 // do something
})

这篇关于.live()vs .on()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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