jQuery: link in append() in click function
I have this:
$('#wallCommentResponse' + wallID).append('<div class="userWallComment"><a id="showCommentLink' + wallID +'" class="showCommentLink" ref="'+ wallID +'" data-id="'+ howMany +'" style="cursor: pointer;">Hide comments</a></div>').show();
INSIDE the click function.
I have this to show a box, with the link 开发者_StackOverflow中文版"hide comments" at the bottom of all the comments. It shows it how i want to, but when i click nothing happens. And i have binded .showCommentLink to
$('.hideWhenShowAll' + wallID).show();
I have another link, just like this, but is not showing by append() but normal HTML, that you also can click on "Hide comments" and it works very well, and its binded to the same function.
So something must be wrong when you append the link, inside the same function that the link triggers on click?
What is wrong? thank you
Change your current .click(func)
to .live('click', func)
, something like this:
$(".showCommentLink").live("click", function() {
$('.hideWhenShowAll' + $(this).attr("ref")).show();
});
This will work for elements added later as well, via .append()
or whatever other method, it's also cheaper when you have many elements. Currently your $(".showCommentLink")
selector is finding elements, binding to them...if they were appended later they don't get the click handler, because the selector didn't find these new elements when it was run.
This article here ... http://jupiterjs.com/news/why-you-should-never-use-jquery-live ... has convinced me to avoid live
in favor of delegate
.
With delegate, your jquery would look something like ...
$('body').delegate('.showCommentLink','click', function(){
$('.hideWhenShowAll' + $(this).attr('ref')).show();
});
I'd like to clear up Nick Craver's answer a bit more.
Once the DOM is loaded everything in...
$(document).ready(function(){
//put js here
});
...is run. If you bind functions to elements, that happens to all then-existing elements. If you add other DOM elements and you want certain functions to bind to them, you can do one of two things. -manually bind them -use .live() as Nick Craver suggests, so binding of new DOM elements happens automagically.
精彩评论