Bugs with jquery.live()?
Can anyone explain to me what's going on?
http://jsfiddle.net/K5yvp/2/
So the way to "achieve" the bugs is :
- Click Show Parent or Show Parent 2
- Click Next to alert
- Click Hide to hide (I even remove the contents with html(''))
- Click Show Parent or Show Parent 2 again
- Click Next
- Bam! Two alerts occur!
- Repeat for more and more alerts to occur
I know the codes I wrote in fiddle is no good, since it's just a simplified version of the problem I found out yesterday. So basically what I meant to do is :
- Show Parent and Show Parent 2 are actually a button to call AJAX to show contents of albums (can be more than 2 of course)
- The < p class="next">Next < /p> is the representation of the data returned from the AJAX request.
- Each of this data can be clicked to do something along with the data returned from the AJAX. On this fiddle, I simply alert 'aaa ' with the title of the Show Parent/ Show Parent 2 (supposed to be "albums"). That's why I include the jquery click event INSIDE the show click event since I need the data passed by the AJAX which is requested inside the show click event (hope this is clear enough)
I've tried some ways to solve this but it's still quite bugging me that my codes are generating bugs(?) . Some of them are :
- Change $('.parent').html(''); to $('.parent').remove(); but of course the div class parent will be gone and I will have to recreate it which is not what I want. Maybe I can do $('.parent *').remove(); to remove all elements inside the parent div, but it's the last resort for me. It's a confusing one since firebug only shows one instance of the < p class="next"> exists at one time.
- Move the next click event outside the show click event. The show click event will store the data returned by AJAX request in a certain div, and the next click event will get the data from this div. A workaround but is there a better way?
Hope this is clear enough. Thanks!
Answers (2)
var title
$('.show').live('click',function(){
title = $(this).attr('title');
$('<p class="next" />').text('next').appendTo($('.parent'));
$('<p class="hide" />').text('hide').appendTo($('.parent'));
$('.parent').fadeIn(500,function(){
});
});
$('.hide').live('click',function(){
$('.parent').empty();
});
$('.next').live('click',function(){
alert('aaa '+title);
return false;
});
The error may lie in your understanding of live
. Live does not run once, and attach a handler to every element it finds. Rather, it allows you to attach handlers to elements that may not exist yet.
So every time this line is hit in your fiddle: $('.next').live('click',function(){
, you're installing another handler to every object with class next
that ever exists, even if that object hasn't yet been created.