简体   繁体   English

OnClientClick事件未触发

[英]OnClientClick event not firing

In the webpage I'm building, I have a div that I need to have hidden by default, and for it to appear when the user clicks on a link button. 在我正在构建的网页中,默认情况下需要隐藏一个div,当用户单击链接按钮时该div才会显示。 This is the code for the link button and the following div: 这是链接按钮和以下div的代码:

    <asp:LinkButton runat="server" Text="Words & stuff go here"
        OnClientClick="button_Click"></asp:LinkButton>

    <div id="Calculator" runat="server" visible="false">
        //CODE GOES IN HERE 
    </div>

And here is the code in the cs file for the link button: 这是cs文件中链接按钮的代码:

void button_Click(object sender, EventArgs e)
    {
        if (Calculator.Visible)
            Calculator.Visible = false;

        else if (!Calculator.Visible)
            Calculator.Visible = true;
    }

I have a breakpoint inside the code behind, and when I debug, the breakpoint is never reached, and I have no idea why. 我在后面的代码中有一个断点,当我调试时,从未到达断点,我也不知道为什么。

on client click is for client side events. 在客户端点击时用于客户端事件。 You have to use onClick="button_Click" to make it work. 您必须使用onClick =“ button_Click”使其起作用。

OnClientClick expects that the button_Click event is defined in javascript on the page, not in C# in the code-behind. OnClientClick希望button_Click事件在页面上的javascript中定义,而不是在后面的代码中的C#中定义。

See this . 看到这个

The OnClientClick property of an ASP .NET control references a client-side function, which means that it will attempt to call a JavaScript function. ASP .NET控件的OnClientClick属性引用一个客户端函数,这意味着它将尝试调用JavaScript函数。

You have two options to fix your code. 您有两种方法可以修复代码。

Option 1: 选项1:
If you want the button to do a Postback and call your button_Click function in your .cs file, you could just change your button code to: 如果希望按钮执行回发并在.cs文件中调用button_Click函数,则只需将按钮代码更改为:

<asp:LinkButton runat="server" Text="Words & stuff go here" OnClick="button_Click"></asp:LinkButton>

Option 2: 选项2:
If you wish to use OnClientClick , you could do something similar to the following (in your .aspx file): 如果希望使用OnClientClick ,则可以执行以下操作(在.aspx文件中):

<script type="text/javascript">
function button_Click() {
  var calculator_id = '<%= Calculator.ClientID %>';
  var calculator = document.getElementById(calculator_id);
  if (calculator.style.display == 'none') {
    calculator.style.display = 'block';
  } else {
    calculator.style.display = 'none';
  }
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM