I am trying to make an "More" after 10 posts of the news topics.
To these news topics, there´s some functions, you can click comment, then appears and you comment without going to another page (AJAX call) and some other like this. This works fine on the first 10 posts.
Now when you click More at the bottom of these 10 news topics, you will get 10 others. Ajax call is used here, and it appends after the 10 first. This works fine too.
But what doesn't work (my issue is that those on click functions I have:
$('.reply').click(function () {
$('#replyWall'+$(this).attr('data-id')).toggle();
document.getElementById('replyMsg'+$(this).attr('data-id')).focus();
});
$('.writeSComment').click(function() {
$(this).hide();
$('#replyToSComment'+$(this).attr('data-id')).toggle();
document.getElementById('commentStatus'+$(this).attr('data-id')).focus();
});
Doesn't work. Maybe is 开发者_开发问答this because the appended comes after the site has loaded, because you first click "More", so it couldn't find any with that id to have this event click on.
But on this appended, there are these id´s, and everything, so is there any way to get these functions working with the appended stuff, or how should i do it?
$('.more').live("click",function() {
var ID = $(this).attr("id");
if(ID) {
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "misc/moreactivities.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html) {
$("#profileWall").append(html);
$("#more"+ID).remove();
}
});
}
});
When you bind an event to a set of selected elements, you're only affecting the elements that currently exist within the DOM. This is what you're doing with .click
, which is an alias for .bind('click', function () { ... });
.
To bind events to all matched elements and newly created elements which match the selector, you need to use .live
:
$('.reply').live('click', function () {
// ...
});
Why are you using native JS functions inside jQuery?
document.getElementById('commentStatus'+$(this).attr('data-id')).focus();
Also if you create elements "on air" use live to attach events
$('.writeSComment').click(function() {
to
$('.writeSComment').live("click", function() {
It'll affect every element, doesn't matter if it was loaded with dom, or later.
//Sorry, I was still writing when poster edited
精彩评论