65.9K
CodeProject 正在变化。 阅读更多。
Home

ClickOnce JavaScript

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (2投票s)

2009年6月25日

CPOL

1分钟阅读

viewsIcon

24742

将一些 JavaScript 添加到项目中,以确保按钮只被单击一次

引言

很多时候,开发者希望点击屏幕上的一个按钮时,禁用屏幕上的其他按钮,以防止多次提交。 附带的是一段提供此功能的 JavaScript 代码。

Using the Code

在互联网上,有很多方法可以防止 ASP.NET 中的多次按钮点击,这只是另一种实现方式。 点击 此处 可以查看一个服务器端控件,它执行与此 JavaScript 类似的操作。

<script language="JavaScript">
<!--
        /// <summary> 
        /// This function disables the submission buttons on the page 
        /// after checking to see if the page's validators are valid.  
        /// If they are not, then the changes don't take place.  
        /// The purpose of this method is to prevent the user from having 
        /// multiple submissions by clicking rapidly on the same button.
        /// </summary>
        function DisableButtonClick(valGroup) {
            // Start the validation false
            var cont = false;

            // Check to see if the page has Validators to fire
            if (typeof Page_ClientValidate != "undefined") {
                // There are validators available, 
	       // so fire them based on the ValidationGroup passed in
                cont = Page_ClientValidate(valGroup);
            }
            else {
                // There are no validators to fire, just disable the buttons
                cont = true;
            }
            // Only continue if the validators are valid or 
	   // there are no validators on the page
            if (cont) {
                // Find a button, and if it exists on this page, then disable it
                var btn = document.getElementById('<%= BtnSaveGeneral.ClientID %>');
                if (btn != null) {
                    btn.disabled = true;
                    btn.value = 'Saving...';
                }
            }
        }
-->
    </script>

这段代码的使用方式是在 HTML 中内联。

<asp:Button ID="BtnSave" runat="server" Text="Save" OnClick="BtnSaveGeneral_Click"
       	OnClientClick="DisableButtonClick('Save');" 
	UseSubmitBehavior="false" ValidationGroup="Save" />

或者在代码隐藏文件中,通过更改按钮的 "onclientclick" 属性。

BtnSave.Attributes.Add("onclientclick", "DisableButtonClick('Save');
BtnSave.UseSubmitBehavior = false;

UseSubmitBehavior 设置为 false ,以便 ASP.NET 渲染 JavaScript,即使 JavaScript 禁用了按钮,也能允许 Button_Click 事件在服务器端触发。

如果需要,也可以发送一个空的 ValidationGroup ,通过发送一个空 string

关注点

这个 JavaScript 函数明确地命名了函数内部要清除的按钮。 其他选项包括在调用 OnClientClick 时将要禁用的按钮传递给函数,或者将要禁用的每个按钮注册到一个数组中,并遍历数组中的名称,禁用找到的每个控件。

历史

  • 2009 年 6 月 25 日:初始发布
© . All rights reserved.