jQuery animate in infinite loop

2019-08-14 07:04发布

问题:

I'm trying to make this happen:

  1. prevent a submit button from submitting the form

  2. fade an element out

  3. then submitting the form

But am stuck with an infinite loop of animation! Why??

HTML

<form id="postitron" method="post" action="/postitron/answertron.php">
  <input type="hidden" name="acces" value"yes">
  <input id="submit" type="submit" value="DOIT">
</form>

JavaScript

$('#postitron').submit(function(e){
    e.preventDefault();
    $('#page').animate({opacity:0},400, function(){
        $('#postitron').submit();
    });
});

P.S.- I've also tried the .one() method instead of .submit(), but it prevents the submit method from being executed on #postitron once the animation's complete :(

回答1:

It is because you are binding your event on SUBMIT, and your .animate callback function is SUBMIT'ing the form...causing the infinite loop.

Try this :

Instead of binding event .submit on form, bind .click event on submit button.

$('#submit').click(function(e){
    e.preventDefault();
    $('#page').animate({opacity:0},400, function(){
        $('#postitron').submit();
    });
});

Bare in mind I did not test this.



回答2:

submit() calls your custom bound submit function, which in turns call your submit again etc.

Try using DOM's submit:

$('#postitron')[0].submit()



回答3:

You could pre-define the function, and within it, unbind to submit, then re-submit. It's a hack, but it may work.

Or perhaps you check for it's hidden-ness and then resubmit like this:

var hidden = false;
$('#postitron').submit(function(e){
    if ( !hidden ) {
        e.preventDefault();
        $('#page').animate({opacity:0},400, function(){
            hidden = true;
            $('#postitron').submit();
        });
    }
});