开发者

Disable onclick until JS function is done

开发者 https://www.devze.com 2023-03-29 16:45 出处:网络
I have a PHP/JS/MySQL driven quiz site with multiple choice questions. The answer alternatives are displayed on four buttons.

I have a PHP/JS/MySQL driven quiz site with multiple choice questions. The answer alternatives are displayed on four buttons.

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

Is there any way to, when a button has been clicked, disable onclick for all buttons until the JS function is complete? As it is now, it's possible for a user to click several alternatives to one question which of course messes up the result.

The JS function called by onclick uses AJAX to call a PHP file which processes the answer.

Many thanks开发者_高级运维


The easiest way to do this is to have some sort of flag value:

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;


Just run your Ajax synchronously.

In jQuery, you just need to add the async=false parameter:

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

精彩评论

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