jQuery 防止多次点击按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16715075/
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-08-26 17:39:07  来源:igfitidea点击:

Preventing multiple clicks on button

javascriptjquery

提问by LCJ

I have following jQuery code to prevent double clicking a button. It works fine. I am using Page_ClientValidate()to ensure that the double click is prevented only if the page is valid. [If there are validation errors the flag should not be set as there is no postback to server started]

我有以下 jQuery 代码来防止双击按钮。它工作正常。我正在使用Page_ClientValidate()以确保仅当页面有效时才阻止双击。[如果存在验证错误,则不应设置该标志,因为没有回发到服务器已启动]

Is there a better method to prevent the second click on the button before the page loads back?

有没有更好的方法来防止在页面加载回来之前第二次点击按钮?

Can we set the flag isOperationInProgress = yesIndicatoronly if the page is causing a postback to server? Is there a suitable eventfor it that will be called before the user can click on the button for the second time?

我们可以isOperationInProgress = yesIndicator仅在页面导致回发到服务器时设置标志 吗?event在用户第二次点击按钮之前,是否有适合它的调用?

Note: I am looking for a solution that won't require any new API

注意:我正在寻找不需要任何新 API 的解决方案

Note: This question is not a duplicate. Here I am trying to avoid the use of Page_ClientValidate(). Also I am looking for an eventwhere I can move the code so that I need not use Page_ClientValidate()

注意:这个问题不是重复的。在这里,我试图避免使用Page_ClientValidate(). 我也在寻找一个event可以移动代码的地方,这样我就不需要使用了Page_ClientValidate()

Note: No ajax involved in my scenario. The ASP.Netform will be submitted to server synchronously. The button click event in javascript is only for preventing double click. The form submission is synchronous using ASP.Net.

注意:我的场景中不涉及 ajax。该ASP.Net表格将被同步提交给服务器。JavaScript 中的按钮单击事件仅用于防止双击。表单提交是使用 ASP.Net 同步的。

Present Code

当前代码

$(document).ready(function () {
  var noIndicator = 'No';
  var yesIndicator = 'Yes';
  var isOperationInProgress = 'No';

  $('.applicationButton').click(function (e) {
    // Prevent button from double click
    var isPageValid = Page_ClientValidate();
    if (isPageValid) {
      if (isOperationInProgress == noIndicator) {
        isOperationInProgress = yesIndicator;
      } else {
        e.preventDefault();
      }
    } 
  });
});

References:

参考资料

  1. Validator causes improper behavior for double click check
  2. Whether to use Page_IsValid or Page_ClientValidate() (for Client Side Events)
  1. 验证器导致双击检查的不当行为
  2. 是否使用 Page_IsValid 或 Page_ClientValidate() (用于客户端事件)

Note by @Peter Ivan in the above references:

@Peter Ivan 在上述参考文献中的注释:

calling Page_ClientValidate() repeatedly may cause the page to be too obtrusive (multiple alerts etc.).

重复调用 Page_ClientValidate() 可能会导致页面过于突兀(多个警报等)。

回答by mauronet

I found this solution that is simple and worked for me:

我发现这个解决方案很简单并且对我有用:

<form ...>
<input ...>
<button ... onclick="this.disabled=true;this.value='Submitting...'; this.form.submit();">
</form>

This solution was found in: Original solution

此解决方案位于: 原始解决方案

回答by Kalyani

JS provides an easy solution by using the event properties:

JS 通过使用事件属性提供了一个简单的解决方案:

$('selector').click(function(event) {
  if(!event.detail || event.detail == 1){//activate on first click only to avoid hiding again on multiple clicks
    // code here. // It will execute only once on multiple clicks
  }
});

回答by Jason

disable the button on click, enable it after the operation completes

单击时禁用按钮,操作完成后启用它

$(document).ready(function () {
    $("#btn").on("click", function() {
        $(this).attr("disabled", "disabled");
        doWork(); //this method contains your logic
    });
});

function doWork() {
    alert("doing work");
    //actually this function will do something and when processing is done the button is enabled by removing the 'disabled' attribute
    //I use setTimeout so you can see the button can only be clicked once, and can't be clicked again while work is being done
    setTimeout('$("#btn").removeAttr("disabled")', 1500);
}

working example

工作示例

回答by plaidcorp

I modified the solutionby @Kalyani and so far it's been working beautifully!

我修改了@Kalyani的解决方案,到目前为止它运行良好!

$('selector').click(function(event) {
  if(!event.detail || event.detail == 1){ return true; }
  else { return false; }
});

回答by Harold

Disable pointer events in the first line of your callback, and then resume them on the last line.

在回调的第一行禁用指针事件,然后在最后一行恢复它们。

element.on('click', function() {
  element.css('pointer-events', 'none'); 
  //do all of your stuff
  element.css('pointer-events', 'auto');   
};

回答by Divya

using count,

使用计数,

 clickcount++;
    if (clickcount == 1) {}

After coming back again clickcount set to zero.

再次回来后,clickcount 设置为零。

回答by user3340312

We can use on and off click for preventing Multiple clicks. i tried it to my application and it's working as expected.

我们可以使用 on 和 off click 来防止多次点击。我在我的应用程序中尝试了它,它按预期工作。

$(document).ready(function () {     
    $("#disable").on('click', function () {
        $(this).off('click'); 
        // enter code here
    });
})

回答by Rish

May be this will help and give the desired functionality :

可能这会有所帮助并提供所需的功能:

$('#disable').on('click', function(){
    $('#disable').attr("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="disable">Disable Me!</button>
<p>Hello</p>

回答by loic.jaouen

use the you should use jQuery's [one][1] :

使用你应该使用 jQuery 的 [one][1] :

.one( events [, data ], handler ) Returns: jQuery

Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

.one( events [, data ], handler ) 返回:jQuery

描述:将处理程序附加到元素的事件。每个事件类型的每个元素最多执行一次处理程序。

see examples:

见例子:

using jQuery: https://codepen.io/loicjaouen/pen/RwweLVx

使用 jQuery:https: //codepen.io/loicjaouen/pen/RwweLVx

// add an even listener that will run only once
$("#click_here_button").one("click", once_callback);

回答by Pixelstix

If you are doing a full round-trip post-back, you can just make the button disappear. If there are validation errors, the button will be visible again upon reload of the page.

如果你正在做一个完整的往返回传,你可以让按钮消失。如果存在验证错误,则在重新加载页面时该按钮将再次可见。

First set add a style to your button:

首先设置为您的按钮添加样式:

<h:commandButton id="SaveBtn" value="Save"
    styleClass="hideOnClick"
    actionListener="#{someBean.saveAction()}"/>

Then make it hide when clicked.

然后让它在点击时隐藏。

$(document).ready(function() {
    $(".hideOnClick").click(function(e) {
        $(e.toElement).hide();
    });
});