問題描述
有誰知道為什么 asp:CheckBox 的客戶端 javascript 處理程序需要是 OnClick="" 屬性而不是 OnClientClick="" 屬性,就像 asp:Button 一樣?
Does anyone know why a client-side javascript handler for asp:CheckBox needs to be an OnClick="" attribute rather than an OnClientClick="" attribute, as for asp:Button?
例如,這是有效的:
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
這沒有(沒有錯誤):
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
但這有效:
<asp:Button runat="server" OnClientClick="alert('Hi');" />
這不是(編譯時錯誤):
and this doesn't (compile time error):
<asp:Button runat="server" OnClick="alert('hi');" />
(我知道 Button.OnClick 的用途;我想知道為什么 CheckBox 不能以同樣的方式工作......)
(I know what Button.OnClick is for; I'm wondering why CheckBox doesn't work the same way...)
推薦答案
這很奇怪.我檢查了 CheckBox 文檔頁面,上面寫著p>
That is very weird. I checked the CheckBox documentation page which reads
<asp:CheckBox id="CheckBox1"
AutoPostBack="True|False"
Text="Label"
TextAlign="Right|Left"
Checked="True|False"
OnCheckedChanged="OnCheckedChangedMethod"
runat="server"/>
如您所見,沒有定義 OnClick 或 OnClientClick 屬性.
As you can see, there is no OnClick or OnClientClick attributes defined.
記住這一點,我認為這就是正在發生的事情.
Keeping this in mind, I think this is what is happening.
當你這樣做時,
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
ASP.NET 不會修改 OnClick 屬性并將其呈現在瀏覽器上.它將被呈現為:
ASP.NET doesn't modify the OnClick attribute and renders it as is on the browser. It would be rendered as:
<input type="checkbox" OnClick="alert(this.checked);" />
顯然,瀏覽器可以理解OnClick"并發出警報.
Obviously, a browser can understand 'OnClick' and puts an alert.
在這種情況下
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
同樣,ASP.NET 不會更改 OnClientClick 屬性并將其呈現為
Again, ASP.NET won't change the OnClientClick attribute and will render it as
<input type="checkbox" OnClientClick="alert(this.checked);" />
由于瀏覽器無法理解 OnClientClick,因此不會發生任何事情.它也不會引發任何錯誤,因為它只是另一個屬性.
As browser won't understand OnClientClick nothing will happen. It also won't raise any error as it is just another attribute.
您可以通過查看呈現的 HTML 來確認上述內容.
You can confirm above by looking at the rendered HTML.
是的,這根本不直觀.
這篇關于OnClick 與 OnClientClick 的 asp:CheckBox?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!