2011-08-20 147 views
0

我有一個PHP/JS/MySQL驅動的測驗網站有多個選擇題。答案選項顯示在四個按鈕上。禁用onclick,直到JS功能完成

<input type = "button" value="$alt1" onClick="changeQuestion('alternative1'); this.style.backgroundColor = '#A9A9A9'"> 

有什麼辦法,當一個按鈕被點擊後,禁用所有按鈕的onclick,直到JS功能完成?就像現在一樣,用戶可以單擊幾個選項來解決一個問題,這當然會弄亂結果。

onclick調用的JS函數使用AJAX調用處理答案的PHP文件。

非常感謝

回答

4

做到這一點,最簡單的方法是有某種標誌值:

var pending = false; 

function changeQuestion(nam) 
{ 
    // test to see if something else set the state to pending. 
    // if so... return, we don't want this to happen. 
    if(pending) return; 
    pending = true; // raise the flag! 

    /* ... later ... */ 
    // in the success method of your AJAX call add: 
    pending = false; 
+0

這是輝煌的。非常感謝你! – Fred

+0

我從HTML按鈕中移動了背景顏色更改腳本,並在JS函數中像這樣添加了它,但這似乎阻止了該函數的運行。它有什麼問題? if(pending)return; pending = true; //舉起旗幟! document.getElementById(answer).style.backgroundColor =「#A9A9A9」; – Fred

0

只要運行在Ajax同步。

在jQuery中,你只需要添加異步= false參數:

$.ajax({ 
    url:'foo.handler.php', 
    data:params, 
    async:false, 
    success:function(){ 
     // do something cool. 
    } 
});