防止在JQuery中第一次执行结束之前进行第二次执行

3
我有以下代码...
$("#myID").click(function(){

    //do some ajax requisition here
    //make it appears in screen with a fadeIn(300)

});

#myID是一个标签的id

但我希望这个函数在实际执行结束之前不要再被调用,我尝试在注释之前和之后放置许多不同的代码,但都没有成功,如果你能帮我防止第二次执行!

fadeIn()不会暂停执行,它的效果发生时会同时执行它之后的代码,有人能帮帮我吗?

谢谢


myID是什么类型的元素?另外,你能否包含所有的代码而不是试图在注释中概括它? - JohnFx
5个回答

4
您可以设置一个标志来存储AJAX函数是否正在运行的状态:
$(function () {

    //set flag to allow AJAX calls
    var AJAX_ok = true;

    //bind click event handler
    $("#myID").click(function(){

        //check if it is ok to run an AJAX request right now
        if (AJAX_ok === true) {

           //if we can run an AJAX request then set the AJAX_ok flag to false so another one does not start
           AJAX_ok = false;

           //make the AJAX call
           $.getJSON('<url>', function (data) {

                //now that the callback function has been called, the AJAX call is done, so we re-enable the AJAX_ok flag
                AJAX_ok = true;

                //make it appears in screen with a fadeIn(300)
                //if DATA is valid HTML then...
                $(data).css('display', 'none').appendTo('#some-container').fadeIn(300);
            });
        }
    });
});

这将仅从#myID元素的click事件处理程序中运行一次AJAX调用。


1

可以把之前的ajax取消掉,或者创建一个布尔变量“running”,当有人点击时,将其设置为true,然后使用if(!running) { //do ajax }来执行ajax操作,在ajax回调中将“running”设置为false。


可以了,谢谢!解决方案非常简单,但我花了几个小时都没有解决问题,非常感谢你! - evandrobm

0

可能有100种更好的方法,但是...

$("#myID").click(function() {
    var is_running = $(this).data('running');

    if (!is_running)
        $(this).data('running', true);
    else
        return;

    /* Do stuff */

    $(this).data('running', false);
}

0
使用回调函数来确保执行顺序。
$("#myID").click(function(){    
     $.ajax({
         url: 'whatever url you are calling',
         success: function(){
             alert('ajax done');   
             $('whatever "it" is').fadeIn(300, function(){
                 //code place here will not execute until after fade in
                 alert('fadeIn done');
             }
        }
     })
});

0

使用同步的 AJAX 调用(默认为异步)。有关如何执行此操作的详细信息,请参见此问题


这是一篇关于如何同步使用getJSON的博客文章:http://www.nurelm.com/themanual/2010/08/09/self-indulgent-code-jquery-getjson-with-error-handling/ - JohnFx
3
我建议不要进行同步的 AJAX 调用,这会导致浏览器一直处于卡顿状态直到调用完成。 - gen_Eric
我同意这是个不好的主意,只是想提供一个选择。 - JohnFx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接