jQuery .live() 和 .on() 有什么区别

发布于 2024-12-14 04:47:12 字数 120 浏览 1 评论 0原文

我看到 jQuery 1.7 中有一个新方法 .on() ,它取代了早期版本中的 .live()

我很想知道它们之间的区别以及使用这种新方法的好处是什么。

I see there's a new method .on() in jQuery 1.7 that replaces the .live() in earlier versions.

I'm interested to know the difference between them and what the benefits are of using this new method.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

吾性傲以野 2024-12-21 04:47:12

docs 中非常清楚为什么您不想使用 live。另外,正如 Felix 所提到的,.on 是一种更简化的附加事件的方式。

以后不再推荐使用.live()方法
jQuery 的版本提供了更好的方法,而它没有
缺点。特别是在使用过程中会出现以下问题:
.live():

  • jQuery 在调用 .live() 方法之前尝试检索选择器指定的元素,这可能是
    处理大型文档非常耗时。
  • 不支持链接方法。例如,$("a").find(".offsite, .external").live( ... ); 是
    无效并且无法按预期工作。
  • 由于所有 .live() 事件都附加在 document 元素上,因此事件花费的时间最长且最慢
    在处理它们之前可能的路径。
  • 调用event.stopPropagation()
    在事件处理程序中对于停止事件处理程序无效
    附在文件下方;该事件已经传播到
    文档
  • .live() 方法以令人惊讶的方式与其他事件方法交互,例如:
    $(document).unbind("click") 删除所有点击处理程序
    通过对 .live() 的任何调用附加!

It's pretty clear in the docs why you wouldn't want to use live. Also as mentioned by Felix, .on is a more streamline way of attaching events.

Use of the .live() method is no longer recommended since later
versions of jQuery offer better methods that do not have its
drawbacks. In particular, the following issues arise with the use of
.live():

  • jQuery attempts to retrieve the elements specified by the selector before calling the .live() method, which may be
    time-consuming on large documents.
  • Chaining methods is not supported. For example, $("a").find(".offsite, .external").live( ... ); is
    not valid and does not work as expected.
  • Since all .live() events are attached at the document element, events take the longest and slowest
    possible path before they are handled.
  • Calling event.stopPropagation()
    in the event handler is ineffective in stopping event handlers
    attached lower in the document; the event has already propagated to
    document.
  • The .live() method interacts with other event methods in ways that can be surprising, e.g.,
    $(document).unbind("click") removes all click handlers
    attached by any call to .live()!
网名女生简单气质 2024-12-21 04:47:12

人们从 .live() 迁移到 .on() 时偶然发现的一个区别是 .on() 的参数略有不同将事件绑定到动态添加到 DOM 的元素时有所不同。

下面是我们用于 .live() 方法的语法示例:

$('button').live('click', doSomething);

function doSomething() {
    // do something
}

现在,.live() 在 jQuery 版本 1.7 中已弃用,并在版本 1.9 中删除,您应该使用 .on() 方法。下面是使用 .on() 方法的等效示例:

$(document).on('click', 'button', doSomething);

function doSomething() {
    // do something
}

请注意,我们是针对文档而不是按钮本身调用 .on()。我们在第二个参数中指定我们正在侦听其事件的元素的选择器。

在上面的示例中,我在文档上调用 .on(),但是如果您使用更靠近选择器的元素,您将获得更好的性能。只要在调用 .on() 之前页面上存在任何祖先元素,它就可以工作。

文档中对此进行了解释,但很容易被忽略。

One difference that people stumble on when moving from .live() to .on() is that the parameters for .on() are slightly different when binding events to elements added dynamically to the DOM.

Here's an example of the syntax we used to use with the .live() method:

$('button').live('click', doSomething);

function doSomething() {
    // do something
}

Now with .live() being deprecated in jQuery version 1.7 and removed in version 1.9, you should use the .on() method. Here's an equivalent example using the .on() method:

$(document).on('click', 'button', doSomething);

function doSomething() {
    // do something
}

Please note that we're calling .on() against the document rather than the button itself. We specify the selector for the element whose events we're listening to in the second parameter.

In the example above, I'm calling .on() on the document, however you'll get better performance if you use an element closer to your selector. Any ancestor element will work so long as it exists on the page before you call .on().

This is explained here in the documentation but it is quite easy to miss.

就像说晚安 2024-12-21 04:47:12

请参阅官方博客

[..]新的 .on() 和 .off() API 统一了所有附加方式
在 jQuery 中将事件发送到文档 - 而且输入起来更短![...]

See the official Blog

[..]The new .on() and .off() APIs unify all the ways of attaching
events to a document in jQuery — and they’re shorter to type![...]

风铃鹿 2024-12-21 04:47:12
.live()

此方法用于为现在和将来与当前选择器匹配的所有元素附加事件处理程序。

$( "#someid" ).live( "click", function() {
  console.log("live event.");
});

.on()

方法用于将一个或多个事件的事件处理函数附加到所选元素,下面是示例。

$( "#someid" ).on( "click", function() {
  console.log("on event.");
});
.live()

This method is used to attach an event handler for all elements which match the current selector, now and in the future.

$( "#someid" ).live( "click", function() {
  console.log("live event.");
});

and

.on()

This method is used to attach an event handler function for one or more events to the selected elements below is the example.

$( "#someid" ).on( "click", function() {
  console.log("on event.");
});
掩于岁月 2024-12-21 04:47:12

关于在线与实时之间差异的好教程

从上面的链接

.live() 有什么问题

以后不再推荐使用.live()方法
jQuery 的版本提供了更好的方法,而它没有
缺点。特别是在使用过程中会出现以下问题:
.live():

  1. jQuery 尝试检索选择器指定的元素
    在调用 .live() 方法之前,这可能会很耗时
    大文档。
  2. 不支持链接方法。例如,
    $(“a”).find(“.offsite,.external”).live( … );无效并且确实
    不按预期工作。
  3. 由于所有 .live() 事件都附加在
    文档元素,事件采用最长且最慢的路径
    在处理它们之前。
  4. 在事件中调用 event.stopPropagation()
    处理程序在停止附加在较低位置的事件处理程序方面无效
    文件;该事件已传播到文档。

  5. .live() 方法与其他事件方法交互的方式可以是
    令人惊讶的是,例如 $(document).unbind(“click”) 删除所有点击
    通过调用 .live() 附加处理程序!

Good tutorial on difference between on vs live

Quote from the above link

What is wrong with .live()

Use of the .live() method is no longer recommended since later
versions of jQuery offer better methods that do not have its
drawbacks. In particular, the following issues arise with the use of
.live():

  1. jQuery attempts to retrieve the elements specified by the selector
    before calling the .live() method, which may be time-consuming on
    large documents.
  2. Chaining methods is not supported. For example,
    $(“a”).find(“.offsite, .external”).live( … ); is not valid and does
    not work as expected.
  3. Since all .live() events are attached at the
    document element, events take the longest and slowest possible path
    before they are handled.
  4. Calling event.stopPropagation() in the event
    handler is ineffective in stopping event handlers attached lower in
    the document; the event has already propagated to document.
  5. The
    .live() method interacts with other event methods in ways that can be
    surprising, e.g., $(document).unbind(“click”) removes all click
    handlers attached by any call to .live()!
油饼 2024-12-21 04:47:12

有关更多信息,请查看.. .live().on()

.live() 方法在处理内容的动态生成时使用...就像我在程序中创建的那样当我更改 Jquery Slider 的值并且我想附加关闭时的选项卡将生成的每个选项卡的按钮功能...我尝试过的代码是..

var tabs = $('#tabs').tabs();
                                        // live() methos attaches an event handler for all
                                        //elements which matches the curren selector
        $( "#tabs span.ui-icon-close" ).live( "click", function() {


            // fetches the panelId attribute aria-control which is like tab1 or vice versa
            var panelId = $( this  ).closest( "li" ).remove().attr( "aria-controls" );
            $( "#" + panelId ).remove();
            tabs.tabs( "refresh" );
        });

并且它的工作原理非常酷...

for more info check it out.. .live() and .on()

.live() method is used when you deal with the dynamic generation of contents... like I have created on program that adds a tab when i change the value of a Jquery Slider and I want to attach the close button functionality to every tabs which will generated... the code i have tried is..

var tabs = $('#tabs').tabs();
                                        // live() methos attaches an event handler for all
                                        //elements which matches the curren selector
        $( "#tabs span.ui-icon-close" ).live( "click", function() {


            // fetches the panelId attribute aria-control which is like tab1 or vice versa
            var panelId = $( this  ).closest( "li" ).remove().attr( "aria-controls" );
            $( "#" + panelId ).remove();
            tabs.tabs( "refresh" );
        });

and it works preety much cool...

风吹过旳痕迹 2024-12-21 04:47:12

我是使用 jQuery 的 Chrome 扩展程序“评论保存”的作者,以及使用 .live() 的一个。该扩展的工作方式是使用 .live() 将侦听器附加到所有文本区域 - 这效果很好,因为每当文档更改时,它仍然会将侦听器附加到所有新的文本区域。

我移至 .on() 但它不起作用。每当文档发生更改时,它都不会附加侦听器 - 因此我已恢复使用 .live()。我猜这是 .on() 中的一个错误。我想只是要小心一点。

I am the author of a Chrome extension "Comment Save" which uses jQuery, and one which used .live(). The way the extension works is by attaching a listener to all the textareas using .live() - this worked well since whenever the document changed it would still attach the listener to all the new textareas.

I moved to .on() but it doesn't work as well. It doesn't attach the listener whenever the document changes - so I have reverted back to using .live(). That is a bug I guess in .on(). Just be careful about it I guess.

烦人精 2024-12-21 04:47:12

我需要识别浏览器关闭事件。在进行研究之后,我正在使用 jQuery 1.8.3

  1. 单击超链接时使用以下 jQuery 打开标志

    $('a').live('click', function() {cleanSession = false;});

  2. 每当单击提交的输入按钮类型时,使用以下 jQuery 打开一个标志

$("input[type=submit] ").live('click',function(){alert('输入按钮被点击');cleanSession=false;});

  1. 当任何时候发生表单提交时,使用以下 jQuery 打开一个标志

$('form').live('submit', function() {cleanSession = false;});

现在重要的是......我的解决方案只有在我使用 .live 而不是 .on 时才有效。如果我使用 .on 那么该事件会在表单提交后被触发,但为时已晚。很多时候,我的表单是使用 javascript 调用 (document.form.submit) 提交的,

因此 .live 和 .on 之间存在关键区别。如果您使用 .live,您的事件会立即触发,但如果您切换到 .on,它不会按时触发

I have a requirement to identify browser closed event. After Doing to of research I am doing following using jQuery 1.8.3

  1. Turn ON a flag using following jQuery when hyperlink is clicked

    $('a').live('click', function() {cleanSession = false;});

  2. Turn ON a flag using following jQuery when any time input button type of submit is clicked

$("input[type=submit]").live('click',function(){alert('input button clicked');cleanSession=false;});

  1. Turn ON a flag using following jQuery when any time form submit happens

$('form').live('submit', function() {cleanSession = false;});

Now important thing...my solution only works if I use .live instead .on. If I use .on then the event gets fired after form gets submitted and which is too late. Many times my forms gets submitted using javascript call (document.form.submit)

So there is a key difference between .live and .on . If you use .live your events get fired immediately but if you switch to .on it doesn't get fired on time

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文