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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8042576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 09:55:09  来源:igfitidea点击:

What's the difference between jQuery .live() and .on()

jqueryjquery-1.7

提问by ajbeaven

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

我看到.on()jQuery 1.7 中有一个新方法可以替代.live()早期版本中的方法。

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

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

回答by aziz punjani

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

文档中很清楚为什么你不想使用 live。同样正如 Felix 所提到的,.on是一种更简化的附加事件的方式。

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 notvalid and does not work as expected.
  • Since all .live()events are attached at the documentelement, 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()!

不再推荐使用 .live() 方法,因为更高版本的 jQuery 提供了没有缺点的更好的方法。特别是,使用 .live() 会出现以下问题:

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

回答by ajbeaven

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.

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

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

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

$('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:

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

$(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.

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

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().

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

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

在文档here中进行了解释但很容易错过。

回答by FloydThreepwood

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![...]

[..]新的 .on() 和 .off() API 统一了在 jQuery 中将事件附加到文档的所有方式——而且它们的输入时间更短![...]

回答by Mohammed Abrar Ahmed

.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.");
});

回答by venkat

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()!

.live() 有什么问题

不再推荐使用 .live() 方法,因为更高版本的 jQuery 提供了没有缺点的更好的方法。特别是,使用 .live() 会出现以下问题:

  1. jQuery 在调用 .live() 方法之前尝试检索选择器指定的元素,这在大型文档上可能很耗时。
  2. 不支持链接方法。例如,$(“a”).find(“.offsite, .external”).live(…); 无效且无法按预期工作。
  3. 由于所有 .live() 事件都附加在文档元素上,因此事件在处理之前会采用最长和最慢的可能路径。
  4. 在事件处理程序中调用 event.stopPropagation() 对停止附加在文档下部的事件处理程序无效;该事件已传播到文档。
  5. .live() 方法以一种令人惊讶的方式与其他事件方法交互,例如,$(document).unbind(“click”) 删除了通过对 .live() 的任何调用附加的所有点击处理程序!

回答by PixelPerfect3

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.

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

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.

我搬到了,.on()但它也不起作用。每当文档更改时,它都不会附加侦听器 - 所以我已经恢复使用.live(). 我猜这是一个错误.on()。我想只要小心点就好了。

回答by Hiren

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

更多信息检查出来.. .live()。对()

.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..

当您处理内容的动态生成时使用 .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" );
        });

and it works preety much cool...

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

回答by N.S.

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

我需要识别浏览器关闭事件。在完成研究之后,我正在使用 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

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

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

  2. 单击任何时间输入按钮类型的提交时,使用以下 jQuery 打开标志

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

$("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
  1. 当表单提交发生时,使用以下 jQuery 打开一个标志

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

$('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)

现在重要的是……我的解决方案只有在我使用 .live 代替 .on 时才有效。如果我使用 .on 则在表单提交后事件被触发,这为时已晚。很多时候我的表单是使用 javascript 调用提交的(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

所以 .live 和 .on 之间有一个关键的区别。如果你使用 .live 你的事件会立即被触发,但如果你切换到 .on 它不会被及时触发