Bug Tracker

Opened 8 years ago

Closed 8 years ago

Last modified 8 years ago

#10340 closed bug (invalid)

jQuery.load and jQuery.live

Reported by: Marcelo Blanco <blancomaberino@…> 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>

Change History (5)

comment:1 Changed 8 years ago by dmethvin

Resolution: invalid
Status: newclosed

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.

comment:2 Changed 8 years ago by Marcelo Blanco <blancomaberino@…>

But that was just an example. Also doing:

jQuery("#loader").empty();

Before doing:

jQuery("#loader").load(page2);

It is the same.

comment:3 Changed 8 years ago by Rick Waldron

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.

comment:4 Changed 8 years ago by Marcelo Blanco <blancomaberino@…>

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,

comment:5 Changed 8 years ago by Rick Waldron

Component: unfiledevent
Priority: undecidedlow

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

Note: See TracTickets for help on using tickets.