javascript 启用按钮只能单击一次异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19053917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:11:23  来源:igfitidea点击:

enable the button to be clicked only to once exception?

javascriptjquery

提问by Ulises Colen

I use a dialog to get the user input, but I found the user may click double click the button and added the content twice, the cause is the dialog fadeout too slow or the user clicked twice on the mouse.. I don't want to adjust the fadeout speed, instead, how to enable the button only can be clicked once?

我使用对话框来获取用户输入,但我发现用户可能会双击按钮并添加两次内容,原因是对话框淡出太慢或用户在鼠标上单击了两次..我不想要调整淡出速度,相反,如何使按钮只能单击一次?

回答by Frédéric Hamidi

jQuery provides the one()method to register a one-shot handler that will only run once.

jQuery 提供one()方法来注册只运行一次的一次性处理程序。

You can write:

你可以写:

$("#yourButton").one("click", function() {
    // Add content...
});

回答by Zathrus Writer

You can disable the button once it was clicked to prevent any further clicks:

您可以在单击按钮后禁用该按钮以防止进一步单击:

$('button').on('click', function() {
    $(this).prop('disabled', true);
});

回答by Joseph Marikle

Here is my suggestion. If you are destroying the dialog on exit, just unbind the click event

这是我的建议。如果您在退出时销毁对话框,只需解除单击事件的绑定

$('.my-button').on('click', function(){
    // process code
    $(this).off('click');
});

You can read about off here

你可以在这里阅读

And here is a demo. First will not allow other clicks but the second will.

这是一个演示。第一个不允许其他点击,但第二个允许。

source

来源

回答by JoshStrange

Here is a Plunkerthat shows how you can do this. Pretty much all you need to do is add the following line in your button:

这是一个Plunker,它展示了如何做到这一点。您几乎需要做的就是在按钮中添加以下行:

onClick="this.disabled = true;"

So that your button HTML will look something like this:

这样您的按钮 HTML 将如下所示:

<button type="submit" onClick="this.disabled = true;">Submit</button>

回答by Themer

try this:

试试这个:

    $('.myButton').click(function(){ 

        $(this).attr('disabled',true);

             ....
    })