简体   繁体   English

JQuery'on'与'live'

[英]JQuery 'on' vs. 'live'

I have a scenario where JQuery 'on' & 'live' do not perform the same. 我有一个场景,JQuery'on'和'live'不会执行相同的操作。 Perhaps someone can point out why. 也许有人可以指出原因。 I am using JQuery 1.7.2 with my project and in this build, 'live' has been replaced with 'on'. 我在我的项目中使用JQuery 1.7.2,在这个版本中,'live'已被'on'取代。 I am using the following code in a listing page. 我在列表页面中使用以下代码。 Basically, this page has an alphabetical bar that the user can click & will load all the clients with that last name. 基本上,此页面有一个字母栏,用户可以单击该栏并将加载具有该姓氏的所有客户端。 I would like the link to execute via ajax. 我想通过ajax执行链接。

Code: 码:

$("a.listajax").on("click", function (e) {
    e.preventDefault();
    var url = $(this).attr("href");
    $("div.content").load(url + " div.content");
    return false;
});

The problem here is that when I first load the page and click on a link, everything works fine. 这里的问题是,当我第一次加载页面并单击链接时,一切正常。 The page gets loaded via ajax. 页面通过ajax加载。 However, after that all the links lose their bindings & then if I click on any links, I get an entire page loads. 但是,之后所有的链接都失去了绑定,然后如果我点击任何链接,我会加载整个页面。

I replaced the 'on' with 'live' and the links started behaving perfectly, even on subsequent clicks. 我将'on'替换为'live',并且链接开始表现完美,即使在后续点击中也是如此。

What am I missing? 我错过了什么?

One does not simply replace .live with .on . 一个不是简单地用.on替换.live

$("a.listajax").live('click', function(e))

Is equivalent to: 相当于:

$(document).on('click', 'a.listajax', function(e))

Important 重要

If there's a common ancestor for all your .listajax anchors that will not be removed from the DOM, you should use that (the deepest one possible) instead of document ; 如果你的所有.listajax锚都有一个共同的祖先,那么你不应该从DOM中删除它,你应该使用它(最深的一个)而不是document ; this will improve performance. 这将提高性能。

That's the whole point of live() . 这就是live() It rebinds new DOM elements when they are created. 它在创建时重新绑定新的DOM元素。 There are a lot of similar questions on jQuery's site, like this one , because it can be a bit confusing. 在jQuery的网站上有很多类似的问题,比如这个 ,因为它可能有点令人困惑。

According to the jQuery docs , you use live() to: 根据jQuery文档 ,您使用live()来:

Attach an event handler for all elements which match the current selector, now and in the future. 为现在和将来与当前选择器匹配的所有元素附加事件处理程序。

The "...in the future" part is key, because on() does not have that . “...在将来”部分是关键,因为on() 没有那个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM