I have a problem with one jQuery script. I use this code:
<span class="follow" data-id="<?=$m['id']; ?>" ></span>
–
$('.follow').click(function(){
$.ajax({
type: "POST",
url:"../ajax/settings/follow.php",
async: false,
dataType:'html',
data: {'id':$(this).attr('data-id')},
success:function(rs){
$(this).removeClass("follow");
$(this).addClass("unfollow");
},
error:function (xhr, ajaxOptions, thrownError){
alert("ERROR !!!");
alert(xhr.status);
alert(ajaxOptions);
alert(thrownError);
}
});
});
After click the span with style image TICK changed to CROSS, and changed attr class to unfollow. After click unfollow class must change to follow, but not working.
$('.unfollow').click(function(){
$.ajax({
type: "POST",
url:"../ajax/settings/follow.php",
async: false,
dataType:'html',
data: {'id':$(this).attr('data-id')},
success:function(rs){
$(this).removeClass("unfollow");
$(this).addClass("follow");
},
error:function (xhr, ajaxOptions, thrownError){
alert("ERROR !!!");
alert(xhr.status);
alert(ajaxOptions);
alert(thrownError);
}
});
});
What’s wrong?
I apologize for my English!
and do same for your follow:
Here one important thing to note that, changing of class not done immediately with click, because you’re changing class within ajax success function, which will take some time to change the class. If you want to change the class instantly on click then take away those change statement outside of ajax success function.
Another important note
When you change the class of
spanthen it becomes dynamic element to DOM. suppose you havespanwith classfollowand onclickevent tospan.followyou change theclasstounfollow. As the.unfollowwas not belong to DOM at page load so it becomes an dynamic element and on ordinary bind will not work here. Same for when you changeclassfromunfollowtofollow.So in both case you need delegate event handler (aka live) event handler like following:
DEMO