What's the difference between jQuery .live() a

2019-01-01 05:35发布

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.

8条回答
谁念西风独自凉
2楼-- · 2019-01-01 06:17

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.

查看更多
其实,你不懂
3楼-- · 2019-01-01 06:20

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()!
查看更多
登录 后发表回答