jQuery : Click and clone bug
Click on a link, then I'd like to execute an animation after cloning an element. But I've unexpected results. To test : http://jsfiddle.net/r4BVb/3/
On multiple link click (like a geek), clone is proceed many times.
$('#clone').click(function(){
$('.view_right').clone().prependTo('.overflowed');
$('.view_right:last').css('display', 'none');
$('.view_right:first').hide('slide', { direction: 'left' }, 300, function() {
$('.view_right:las开发者_运维技巧t').show('slide', { direction: 'right' }, 300, function() {
$('.view_right:first').remove();
});
});
});
How can I solve this ? Thanks
Here is the solution:
var called = false;
$('#clone').click(function(){
if (called) {
return;
}
called = true;
$('.view_right').clone().prependTo('.overflowed');
$('.view_right:last').css('display', 'none');
$('.view_right:first').hide('slide', { direction: 'left' }, 300, function() {
$('.view_right:last').show('slide', { direction: 'right' }, 300, function() {
$('.view_right:first').remove();
called = false;
});
});
});
Test it
Your code will add a lot of clones to view_right, so I suggest to check you're not adding too many like this:
if($('.view_right').length < 2) {
And the result will be http://jsfiddle.net/r4BVb/7/
Check this out: Using .one()
I'm effectively rebinding the click after animation and only listening to the click event once.
精彩评论