jQuery .live('click')与.click() [英] jquery .live('click') vs .click()

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

问题描述

我想知道在任何情况下使用.click(function {...});而不是.live('click', function {...});会更好吗?

I am wondering whether there are any circumstances where it would be better to use .click(function {...}); rather than .live('click', function {...});?

从我收集到的信息来看,live选项似乎是一个更好的选择,因此我在几乎所有情况下都使用了live选项,而不是普通的.click(),尤其是考虑到我的许多代码都是异步加载的.

From what I gather the live option seems to be a better option and I am hence using it in almost all circumstances instead of the plain .click(), especially given a lot of my code is loaded asynchronously.

这个问题的另一部分.如果我异步加载所有JavaScript,则.click仍会拾取dom中已经存在的所有元素.对吧?

Another part to this question. If I'm asynchoronously loading all the javascript in, .click will still pickup all elements already in the dom. Right?

推荐答案

有时,您可能明确希望仅将单击处理程序分配给已存在的对象,并以不同的方式处理新对象.但更常见的是,生活并不总是可行.它不适用于链式jQuery语句,例如:

There might be times when you explicitly want to only assign the click handler to objects which already exist, and handle new objects differently. But more commonly, live doesn't always work. It doesn't work with chained jQuery statements such as:

$(this).children().live('click',doSomething);

由于事件在DOM树中起泡的方式,它需要选择器才能正常工作.

It needs a selector to work properly because of the way events bubble up the DOM tree.

编辑:有人刚刚对此表示赞同,因此显然人们还在关注它.我应该指出,livebind均已已弃用.您可以同时使用 .on() 来执行这两种操作,这是IMO更加清晰的语法.替换bind:

Someone just upvoted this, so obviously people are still looking at it. I should point out that live and bind are both deprecated. You can perform both with .on(), which IMO is a much clearer syntax. To replace bind:

$(selector).on('click', function () {
    ...
});

并替换live:

$(document).on('click', selector, function () {
    ...
});

除了使用$(document)之外,您还可以使用包含所有要监视点击的元素的jQuery对象,但是在调用它时相应的元素必须存在.

Instead of using $(document), you can use any jQuery object which contains all the elements you're monitoring the clicks on, but the corresponding element must exist when you call it.

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

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