简体   繁体   中英

Disable onclick until JS function is done

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.
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM