asp:CheckBox 的 OnClick 与 OnClientClick?

发布于 2024-07-27 23:06:22 字数 616 浏览 7 评论 0原文

有谁知道为什么 asp:CheckBox 的客户端 javascript 处理程序需要是 OnClick="" 属性,而不是像 asp:Button 那样的 OnClientClick="" 属性?

例如,这有效:

<asp:CheckBox runat="server" OnClick="alert(this.checked);" />

这不起作用(没有错误):

<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />

但这有效:

<asp:Button runat="server" OnClientClick="alert('Hi');" />

这不起作用(编译时错误):(

<asp:Button runat="server" OnClick="alert('hi');" />

我知道 Button.OnClick 的用途;我想知道为什么 CheckBox 不以同样的方式工作...)

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?

For example, this works:

<asp:CheckBox runat="server" OnClick="alert(this.checked);" />

and this doesn't (no error):

<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />

but this works:

<asp:Button runat="server" OnClientClick="alert('Hi');" />

and this doesn't (compile time error):

<asp:Button runat="server" OnClick="alert('hi');" />

(I know what Button.OnClick is for; I'm wondering why CheckBox doesn't work the same way...)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

初雪 2024-08-03 23:06:22

这很奇怪。 我检查了 CheckBox 文档页面,内容为

<asp:CheckBox id="CheckBox1" 
     AutoPostBack="True|False"
     Text="Label"
     TextAlign="Right|Left"
     Checked="True|False"
     OnCheckedChanged="OnCheckedChangedMethod"
     runat="server"/>

As you可以看到,没有定义OnClick 或OnClientClick 属性。

记住这一点,我认为这就是正在发生的事情。

当您执行此操作时,

<asp:CheckBox runat="server" OnClick="alert(this.checked);" />

ASP.NET 不会修改 OnClick 属性并按原样在浏览器上呈现它。 它将呈现为:

  <input type="checkbox" OnClick="alert(this.checked);" />

显然,浏览器可以理解“OnClick”并发出警报。

在这种情况下

<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />

,ASP.NET 不会更改 OnClientClick 属性,并将其呈现为

<input type="checkbox" OnClientClick="alert(this.checked);" />

由于浏览器无法理解 OnClientClick,因此什么也不会发生。 它也不会引发任何错误,因为它只是另一个属性。

您可以通过查看呈现的 HTML 来确认上述内容。

是的,这根本不直观。

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"/>

As you can see, there is no OnClick or OnClientClick attributes defined.

Keeping this in mind, I think this is what is happening.

When you do this,

<asp:CheckBox runat="server" OnClick="alert(this.checked);" />

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);" />

Obviously, a browser can understand 'OnClick' and puts an alert.

And in this scenario

<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />

Again, ASP.NET won't change the OnClientClick attribute and will render it as

<input type="checkbox" OnClientClick="alert(this.checked);" />

As browser won't understand OnClientClick nothing will happen. It also won't raise any error as it is just another attribute.

You can confirm above by looking at the rendered HTML.

And yes, this is not intuitive at all.

千年*琉璃梦 2024-08-03 23:06:22

因为它们是两种不同类型的控件...

您看,您的网络浏览器不了解服务器端编程。 它只知道它自己的 DOM 和它使用的事件模型......以及渲染给它的对象的单击事件。 您应该检查实际从 ASP.Net 发送到浏览器的最终标记,以了解您自己的差异。

<asp:CheckBox runat="server" OnClick="alert(this.checked);" />

如有疑问,请始终

<input type="check" OnClick="alert(this.checked);" />

在发送到

<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />

现在

<input type="check" OnClientClick="alert(this.checked);" />

,据我所知,没有任何浏览器在其 DOM 中支持“OnClientClick”事件...

浏览器时查看输出的来源...您可以看到大量的调试信息。

Because they are two different kinds of controls...

You see, your web browser doesn't know about server side programming. it only knows about it's own DOM and the event models that it uses... And for click events of objects rendered to it. You should examine the final markup that is actually sent to the browser from ASP.Net to see the differences your self.

<asp:CheckBox runat="server" OnClick="alert(this.checked);" />

renders to

<input type="check" OnClick="alert(this.checked);" />

and

<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />

renders to

<input type="check" OnClientClick="alert(this.checked);" />

Now, as near as i can recall, there are no browsers anywhere that support the "OnClientClick" event in their DOM...

When in doubt, always view the source of the output as it is sent to the browser... there's a whole world of debug information that you can see.

策马西风 2024-08-03 23:06:22

你说得对,这是不一致的。 发生的情况是 CheckBox 没有服务器端 OnClick 事件,因此您的标记将呈现到浏览器。 http://msdn.microsoft.com/en -us/library/system.web.ui.webcontrols.checkbox_events.aspx

而 Button 确实有 OnClick - 因此 ASP.NET 需要对 OnClick 标记中的事件的引用。

You are right this is inconsistent. What is happening is that CheckBox doesn't HAVE an server-side OnClick event, so your markup gets rendered to the browser. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox_events.aspx

Whereas Button does have a OnClick - so ASP.NET expects a reference to an event in your OnClick markup.

不交电费瞎发啥光 2024-08-03 23:06:22

对于那些来这里寻找服务器端OnClick处理程序的人来说,它是OnCheckedChanged

For those of you who got here looking for the server-side OnClick handler it is OnCheckedChanged

千纸鹤带着心事 2024-08-03 23:06:22

我正在清理警告和消息,发现 VS 确实发出了警告:
验证 (ASP.Net):属性“OnClick”不是元素“CheckBox”的有效属性。 使用 html 输入控件指定客户端处理程序,然后您将不会获得额外的 span 标记和两个元素。

I was cleaning up warnings and messages and see that VS does warn about it:
Validation (ASP.Net): Attribute 'OnClick' is not a valid attribute of element 'CheckBox'. Use the html input control to specify a client side handler and then you won't get the extra span tag and the two elements.

抹茶夏天i‖ 2024-08-03 23:06:22

您可以像这样执行标记:

<asp:CheckBox runat="server" ID="ckRouteNow" Text="Send Now" OnClick="checkchanged(this)" />

被调用的 JavaScript 中的 .checked 属性将是正确的...复选框的当前状态:

  function checkchanged(obj) {
      alert(obj.checked)
  }

You can do the tag like this:

<asp:CheckBox runat="server" ID="ckRouteNow" Text="Send Now" OnClick="checkchanged(this)" />

The .checked property in the called JavaScript will be correct...the current state of the checkbox:

  function checkchanged(obj) {
      alert(obj.checked)
  }
挥剑断情 2024-08-03 23:06:22

Asp.net CheckBox 不支持 OnClientClick 方法。
如果您想向 asp:CheckBox 添加一些 javascript 事件,您必须在服务器代码中的“Pre_Render”或“Page_Load”事件上添加相关属性:

C#:

    private void Page_Load(object sender, EventArgs e)
    {
        SomeCheckBoxId.Attributes["onclick"] = "MyJavaScriptMethod(this);";
    }

注意:确保您没有在页眉中设置 AutoEventWireup="false"。

VB:

    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SomeCheckBoxId.Attributes("onclick") = "MyJavaScriptMethod(this);"
    End Sub

Asp.net CheckBox is not support method OnClientClick.
If you want to add some javascript event to asp:CheckBox you have to add related attributes on "Pre_Render" or on "Page_Load" events in server code:

C#:

    private void Page_Load(object sender, EventArgs e)
    {
        SomeCheckBoxId.Attributes["onclick"] = "MyJavaScriptMethod(this);";
    }

Note: Ensure you don't set AutoEventWireup="false" in page header.

VB:

    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SomeCheckBoxId.Attributes("onclick") = "MyJavaScriptMethod(this);"
    End Sub
两相知 2024-08-03 23:06:22

您可以将功能分配给所有复选框,然后在其中要求确认。 如果他们选择“是”,则允许更改复选框,如果选择“否”则保持不变。

就我而言,我还在中继器(或网格)内使用具有 Autopostback="True" 属性的 ASP .Net 复选框,因此在服务器端,我需要将提交的值与数据库中当前的值进行比较,以便了解它们的确认值仅当选择“是”时才选择并更新数据库。

$(document).ready(function () {
    $('input[type=checkbox]').click(function(){                
        var areYouSure = confirm('Are you sure you want make this change?');
        if (areYouSure) {
            $(this).prop('checked', this.checked);
        } else {
            $(this).prop('checked', !this.checked);
        }
    });
}); 


<asp:CheckBox ID="chk" AutoPostBack="true" onCheckedChanged="chk_SelectedIndexChanged" runat="server" Checked='<%#Eval("FinancialAid") %>' />

protected void chk_SelectedIndexChanged(Object sender, EventArgs e)
{
    using (myDataContext db = new myDataDataContext())
    {
        CheckBox chk = (CheckBox)sender;
        RepeaterItem row = (RepeaterItem) chk.NamingContainer;            
        var studentID = ((Label) row.FindControl("lblID")).Text;
        var z = (from b in db.StudentApplicants
        where b.StudentID == studentID
        select b).FirstOrDefault();                
        if(chk != null && chk.Checked != z.FinancialAid){
            z.FinancialAid = chk.Checked;                
            z.ModifiedDate = DateTime.Now;
            db.SubmitChanges();
            BindGrid();
        }
        gvData.DataBind();
    }
}

You can assign function to all checkboxes then ask for confirmation inside of it. If they choose yes, checkbox is allowed to be changed if no it remains unchanged.

In my case I am also using ASP .Net checkbox inside a repeater (or grid) with Autopostback="True" attribute, so on server side I need to compare the value submitted vs what's currently in db in order to know what confirmation value they chose and update db only if it was "yes".

$(document).ready(function () {
    $('input[type=checkbox]').click(function(){                
        var areYouSure = confirm('Are you sure you want make this change?');
        if (areYouSure) {
            $(this).prop('checked', this.checked);
        } else {
            $(this).prop('checked', !this.checked);
        }
    });
}); 


<asp:CheckBox ID="chk" AutoPostBack="true" onCheckedChanged="chk_SelectedIndexChanged" runat="server" Checked='<%#Eval("FinancialAid") %>' />

protected void chk_SelectedIndexChanged(Object sender, EventArgs e)
{
    using (myDataContext db = new myDataDataContext())
    {
        CheckBox chk = (CheckBox)sender;
        RepeaterItem row = (RepeaterItem) chk.NamingContainer;            
        var studentID = ((Label) row.FindControl("lblID")).Text;
        var z = (from b in db.StudentApplicants
        where b.StudentID == studentID
        select b).FirstOrDefault();                
        if(chk != null && chk.Checked != z.FinancialAid){
            z.FinancialAid = chk.Checked;                
            z.ModifiedDate = DateTime.Now;
            db.SubmitChanges();
            BindGrid();
        }
        gvData.DataBind();
    }
}
挽手叙旧 2024-08-03 23:06:22

一种解决方案是使用 JQuery:

$(document).ready(
    function () {
        $('#mycheckboxId').click(function () {
               // here the action or function to call
        });
    }
);

One solution is with JQuery:

$(document).ready(
    function () {
        $('#mycheckboxId').click(function () {
               // here the action or function to call
        });
    }
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文