Side navigation
#10340 closed bug (invalid)
Opened September 24, 2011 11:47PM UTC
Closed September 25, 2011 12:00AM UTC
Last modified September 25, 2011 03:18PM UTC
jQuery.load and jQuery.live
Reported by: | Marcelo Blanco <blancomaberino@gmail.com> | Owned by: | |
---|---|---|---|
Priority: | low | Milestone: | None |
Component: | event | Version: | 1.6.4 |
Keywords: | Cc: | ||
Blocked by: | Blocking: |
Description
When loading a page inside a div, using jQuery.load(), each time this page is loaded, all the events loaded inside it (using jQuery.live) are loaded again. So, if i have a button in the page and i load it again, the button will have attached two events.
Example:
Page 1 -
<div id="loader"></div> <script> jQuery("#loader").load(page2); // When i click on the button, it shows the alert once. // I load the page again jQuery("#loader").load(page2); // When i click on the button, it shows the alert twice. // It is going to show the alert many times as i load page2 </script>
Page 2 -
<button id="foo">Click Me</button> <script> jQuery("#foo").live('click', function(){alert("inside");}); </script>
Attachments (0)
Change History (5)
Changed September 25, 2011 12:00AM UTC by comment:1
resolution: | → invalid |
---|---|
status: | new → closed |
Changed September 25, 2011 02:28AM UTC by comment:2
But that was just an example. Also doing:
jQuery("#loader").empty();
Before doing:
jQuery("#loader").load(page2);
It is the same.
Changed September 25, 2011 01:39PM UTC by comment:3
Either way you slice it, the behaviour is exactly what I would expect from the code you've shown. Put the live handler in the parent document to avoid multiple reattachment.
Changed September 25, 2011 02:51PM UTC by comment:4
Ok, putting the live handler in the parent document, it works fine. But it should work fine having it on the children document. Doesn't it? Because I need to add a lot of pages to the parent (it acts like a template) and if i add all the handlers there, it will take more to load the page for first time.
Thanks,
Changed September 25, 2011 03:18PM UTC by comment:5
component: | unfiled → event |
---|---|
priority: | undecided → low |
Separation of concerns: your logic shouldn't be buried in your markup - that's just sloppy code. The whole point of live
and delegate
is so that you can have them declared once in a source file and when you add elements to the page that match the live or delegate selectors, your program will know what to do.
This is absolutely not a bug -- if you attach 1 handler, 1 handler will be executed when the event occurs. If you attach 10 handlers, 10 handlers will execute when the event occurs.
Any further questions about this should be directed to the forums: http://forum.jquery.com/getting-started
By adding page2 multiple times, you're creating an invalid document that has duplicate
id="foo"
elements. Please ask for help on http://forum.jquery.com if you need further assistance.