禁用点击一个按钮 [英] Disable a button on click

查看:188
本文介绍了禁用点击一个按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮控制。一旦用户点击就可以了,点击事件应该火再按钮应该禁用。我怎样才能做到这一点?我使用jQuery或JavaScript或两个选项。

下面是我的按钮声明:

 < ASP:按钮
  ID =Button1的
  =服务器
  文本=点击我
  的onclick =的button1_Click
/>

点击按钮code后面,我添加了一个回复于()。这应该得到执行,然后该按钮应该被禁用。


解决方案

简短的回答:

诀窍回发时禁用Button控件是使用UseSubmitBehavior =假

龙答:

无论出于何种原因, HTML规范决定了被禁用的元素不应该被包含在POST请求的。所以,如果你使用JavaScript来禁用客户端onclick事件的HTML元素,输入元素将在浏览器组装POST请求关闭,服务器将无法正确通知其元素引发回发,并且它赢得T火服务器端单击事件处理程序。

当您设置的 UseSubmitBehavior 属性设置为false,ASP.NET呈现键入按钮的输入元素而不是类型的常规输入提交的ASP.NET Button控件通常生成。因为点击一个按钮元素不会触发浏览器的表单提交事件这是很重要的。

而不是依赖于浏览器表单提交,ASP.NET将呈现一个客户端调用__doPostBack()该按钮元素的onclick处理程序中。 __doPostBack将提高回发明确,无论在什么样的要求POST数据来通过。

通过回传被提出独立于浏览器的submit事件,你释放pviously提到HTML怪癖的$ P $的。然后,您可以设置的OnClientClick的this.disabled = TRUE;,这将呈现为this.disabled = TRUE; __doPostBack('Button1的','');,并如预期事情会工作。

I have a button control. Once the user clicks on it, the click event should fire and then the button should get disabled. How can I do this? I have the option to use JQuery or JavaScript or both.

Here is my button declaration:

<asp:Button 
  ID="Button1" 
  runat="server" 
  Text="Click Me" 
  onclick="Button1_Click"
/> 

On the button click code behind, I have added a Response.Write(). That should get executed and then the button should be disabled

解决方案

Short answer:

The trick to disabling a Button control during a postback is to use UseSubmitBehavior=false.

Long answer:

For whatever reason, the HTML spec dictates that disabled elements should not be included in POST requests. So, if you use JavaScript to disable the HTML element in the client-side onclick event, the input element will be disabled when the browser assembles the POST request, the server won't be properly notified which element raised the postback, and it won't fire server-side click event handlers.

When you set the UseSubmitBehavior property to false, ASP.NET renders an input element of type button instead of the regular input of type submit that the ASP.NET Button control normally generates. This is important because clicking a button element does not trigger the browser's form submit event.

Instead of relying on a browser form submission, ASP.NET will render a client-side call to __doPostBack() within that button element's onclick handler. __doPostBack will raise the postback explicitly, regardless of what POST data comes through in the request.

With the postback being raised independent of the browser submit event, you're freed of the previously mentioned HTML quirk. Then, you can set an OnClientClick of "this.disabled = true;", which will render as "this.disabled = true; __doPostBack('Button1', '');", and things will work as intended.

这篇关于禁用点击一个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆