当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Disabling an element from being clicked after it is clicked

问题描述:

I have a button that saves the content that a user edits. I do not want them to hit the save button multiple times because of the load it causes on the server. I want to disable the button after they click on it.

Here is what I have attempted(doesn't work, though):

 var active = true;

$("#save").click(function() {

if (!active) return;

active = false;

........

........

........

active = true;

The problem is that the user can still click on the element multiple times.

How can I fix this problem?

Edit: Sorry, I forgot to mention that I want to enable the click after the onclick code has finished executing.

网友答案:

Try this

$("#save").one('click', function() {
    //this function will be called only once even after clicking multiple times
});
网友答案:

There is a disabled attribute: http://jsfiddle.net/uM9Md/.

  $("#save").click(function() {
    $(this).attr('disabled', true)
........
........
........
    $(this).attr('disabled', false)
  });
网友答案:

You can unbind the click handler, but I would go with .one as per @ShankarSangoli's answer (+1).

$("#save").click(function() {

    // do things

    $(this).unbind("click");

});

http://api.jquery.com/unbind/

网友答案:

If the element is an input you can do this really easily:

<input name="BUTTON" type="submit" value="Submit" onSubmit="document.BUTTON.disabled = true;">

That's some handy HTML Javascript integration stuff there.

网友答案:

Assuming:

<input type="button" id="save" ... />

You can either do:

$('#save').click(function(){
    var $save = $(this);

    //
    // save code
    //

    $save.get(0).disabled = true;
});

Which disabled the button natively, or you can use jQuery's one functionality:

$('#save').one('click',function(){
    //
    // save code
    //
});

Which will only execute once and must be re-bound. (But if you're deciding to enable/disable based on parameters, using the disabled attribute is probably a better choice.)

分享给朋友:
您可能感兴趣的文章:
随机阅读: