2012-07-16 91 views
0

我的頁面中有一個鏈接,當用戶點擊此鏈接時,我將加載一些數據與$.getJSON,如果服務器忙或網速低,這個響應將會大約需要10秒鐘,因此可能會再次點擊此鏈接的用戶,我如何更改我的代碼以防止第二次點擊?我的意思是,如何定義用戶是否在鏈接上第二次點擊,什麼都不要?防止數據仍在加載時發生第二次點擊

這是Click事件:

$('#showResult').click(function() { 
    $.getJSON (url, data, function updateForm() { 

     .... MY CODE .... 

    }); 
}); 

對不起,我英文不好:-(

+0

可以禁用按鈕,當成功獲取數據,您啓用 – Ricky 2012-07-16 11:57:22

回答

1

您可以嘗試解除綁定一下,像

$('#showResult').click(function() { 
    $(this).unbind("click"); 
    $.getJSON (url, data, function updateForm() { 

     .... MY CODE .... 
     //after response data you can rebind it 

    }); 
}); 

OR 你可以添加一些屬性並檢查它,就像在點擊後添加「點擊」數據一樣

$('#showResult').click(function() { 
    if($(this).data("clicked") { 
     return false; 
    } 
    else { 
     $.getJSON (url, data, function updateForm() { 

     .... MY CODE .... 
     $('#showResult').data("clicked", true); 
     }); 
    } 
}); 
2

你可以做這樣的事情:

$('#showResult').click(function() { 
    var _this = this; 
    if (this.inprogress) { 
     alert('please wait'); 
     return; 
    } 
    this.inprogress = true; 
    $.getJSON (url, data, function updateForm() { 

     .... MY CODE .... 
     _this.inprogress= false; 
    }); 
}); 

但通常我更喜歡有顯示進度微調,當我有一個正在長裝,讓用戶知道他已經變灰整個窗口等待:

loading = { 
    count: 0 
}; 

loading.finish = function() { 
    this.count--; 
    if (this.count==0) this.$div.hide(); 
}; 

loading.start = function() { 
    this.count++; 
    if (!this.$div) { 
     var html = '<div style="position: fixed;z-index:100;left:0;top:0;right:0;bottom:0;background: black;opacity: 0.6;">'; // this class covers and greys the whole page 
     html += '<table width=100% height=100%>'; 
     html += '<tr><td align=center valign=middle>'; 
     html += '<img src=img/loading.gif>'; 
     html += '</td></tr>'; 
     html += '</table></div>'; 
     this.$div=$(html); 
     this.$div.prependTo('body'); 
    } 
    setTimeout(function(){ 
     if (loading.count>0) loading.$div.show(); 
    }, 500); 
}; 

$('#showResult').click(function() { 
    loading.start(); 
    $.getJSON (url, data, function updateForm() { 

     .... MY CODE .... 

     loading.finish(); 
    }); 
}); 

(使用此代碼時,只有在ajax調用時間超過500毫秒時才顯示微調器)。

1

此代碼應該捕捉元素上的雙擊並防止該事件冒泡。

$("#showResult").on('dblclick',function(e){ 
    e.preventDefault(); 
}); 

如果您只是想在發生某些其他操作時阻止第二次單擊,則可以使用布爾標誌。類似於isWorking

var isWorking = false; 

$("#showResult").on('click',function(){ 
    if (!isWorking){ 
    //execute code here! 
    isWorking = true; 
    }else{ 
    // wait! something is still working! 
    } 
}); 

不要忘記在動作完成後將你的旗返回到原來的位置。

isWorking = false;

0
var doJson = function(doCallback) { 
    $('#showResult').unbind('click'); 
    $.getJSON (url, data, function updateForm() { 
     .... MY CODE .... 
     doCallback(); 
    }); 
} 

$('#showResult').click(function() { 
    doJson(function() { 
     $('#showResult').bind('click', this)); 
    }); 
}); 

回調綁定功能,該功能解除綁定吧:)