开发者

jQuery: having trouble with code to disable link after ajax event

Goal: Disable links before ajax:success is received. (then i'll tell my app server thing to enable the links. I'm writing a si开发者_如何学Pythonmple board game, and don't want to be recieving multiple ajax requests before the first one is responded to, because it messes with the game logic.

  <script type="text/javascript">
      var disableLinks = false;

  $("a").click(function(e){
    if (disableLinks){
      e.preventDefault();
    }
  });


  $("a").ajaxStart(function(){
    disableLinks = true;
  });

    $("a").ajaxStop(function(){
    disableLinks = false;
  });


</script>

And here are what the links look like:

<a href="/board/take_turn?id=313&x=1&y=2" data-remote="true">
              <div class="ttt_square"> 
                &nbsp;
              </div>
</a>


This is because your AJAX start and finish events never fire. Why? Because simply clicking a link isn't an AJAX request, and doesn't trigger the global AJAX events. To use the global AJAX events, you need to use an AJAX function such as .get( ), .load( ), or $.ajax( )

The code below, is mostly yours... I've just added 2 lines (which could even be reduced to 1, but I think it looks better this way)

var disableLinks = true;

$('a').click( function( e )
{
    if( disableLinks )
    {
        e.preventDefault( );
    }

    var self = $(this);
    $.ajax( { "url": self.attr( 'href' ) } );
} );


$('a').ajaxStart( function( )
{
    disableLinks = true;
} );

$('a').ajaxStop( function( )
{
    disableLinks = false;
} );


You've got a typo. e.prevenDefault(); should be e.preventDefault();

And this should be enough for disabling the default action. So you can rid of your onclick.

$("a").click(function(e){
    e.preventDefault();
});

Edit: Maybe this: jQuery - How can I temporarily disable the onclick event listener after the event has been fired?

or this: jQuery - How can I temporarily disable the onclick event listener after the event has been fired?

should solve your problem (if understand you correctly)


try this:

$('a').click(function(){
    if (!this.hasClass('disabled')) {
        this.addClass('disabled');
        var self = this;
        $.ajax({url: this.attr('href'),
                complete: function(jqXHR, textStatus)
                   self.removeClass('disabled');
                }
        });

    }
    return false;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜