jQuery animate in infinite loop

2019-08-14 06:59发布

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 :(

3条回答
冷血范
2楼-- · 2019-08-14 07:30

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.

查看更多
倾城 Initia
3楼-- · 2019-08-14 07:49

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();
        });
    }
});
查看更多
一纸荒年 Trace。
4楼-- · 2019-08-14 07:51

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

Try using DOM's submit:

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

查看更多
登录 后发表回答