I can’t understand this.
When I want to remove class B from a div and add class D into it,
It works.
But class D‘s function can’t be triggered.
$('.B').click(function() {
$('.A').animate({
"left": "+=10%"
},{
duration:1000,
complete: function(){
$("#C").addClass("D").removeClass("B");
}
});
});
$(".D").click(function() {
$(".A").animate({
"top":"+=40%"
},{
duration:2000,
complete:function(){
$("#C").addClass("B").removeClass("D");
}
});
});
I’ve tried putting class D‘s function into class B‘s function like this:
$('.B').click(function() {
$('.A').animate({
"left": "+=10%"
},{
duration:1000,
complete: function(){
$("#C").addClass("D").removeClass("B");
$(".D").click(function() {
$(".A").animate({
"top":"+=40%"
},{
duration:2000,
complete:function(){
$("#C").addClass("B").removeClass("D");
}
});
});
}
});
});
and both functions work for the first time and after that they behavior in a bizarre way.
I would appreciate if someone can explain to me why and provide me with a solution.
When you use
$.click, you bind only to the elements that match the select at that time. If you want to match all future elements as well, use$.oninstead:This will react whether the clicked element had
class="D"to begin with, or if it acquired it later on through something like$(this).addClass("D").The
"body"part ideally should be a container much closer to your clicked elements. For instance, if you had the following:You should use
#containerinstead ofbodyin the jQuery function.