【问题标题】:convert c# button click to script将 c# 按钮单击转换为脚本
【发布时间】:2013-08-02 15:35:39
【问题描述】:

谁能帮我把这个 C# 代码转换成脚本?

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

protected void Button1_Click(object sender, EventArgs e)
    {
        Session["ctrl"] = Panel1;
        ClientScript.RegisterStartupScript(this.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx','PrintMe','height=300px,width=300px,scrollbars=1');</script>");
    }

【问题讨论】:

    标签: c# javascript jquery-ui button


    【解决方案1】:

    您可以使用&lt;%=Button1.ClientID%&gt; 获取 Html DOM ID

    使用 jQuery 你会得到:

    $(function() {
        $("#<%=Button1.ClientID%>").click(function() {
            window.open(...)
        });
    });
    

    当然,也许您不想使用服务器控件并将按钮和行为保留在客户端。

    <input type='button' value='Button' id='Button1' />
    

    然后使用与上面相同的构造:$("Button1").click(...)

    【讨论】:

      【解决方案2】:

      如果您只是想让它成为普通的 html / javascript,它只是一个按钮的 onclick 事件。但是,通过将其更改为 javascript,您将丢失会话变量“ctrl”的集合。这可能会被应用程序的其他部分使用。如果您不在乎,那么您可以更改为常规的 html 按钮。如果您确实关心会话变量,那么您必须使用服务器端代码(例如 c#)来设置会话变量(例如您在上面发布的 c# 代码)。

      我会这样理解:

      <input type="button" id="button1" name="button1" value="Button" onclick="javascript:window.open('Print.aspx','PrintMe','height=300px,width=300px,scrollbars=1');" />
      

      如果你想整理你的 html 代码,你也可以将点击事件包装到一个函数中。

      如果您不喜欢在按钮中使用 javascript,您可以随时将 onclick 与 javascript 绑定。​​

      例如,如果你有 jquery 库,你可以这样做:

      $(document).ready(function() {
            $("#button1").on("click","window.open('Print.aspx','PrintMe','height=300px,width=300px,scrollbars=1'));
      });
      

      【讨论】:

      • 谢谢Avitus,它有帮助,但是如何控制点击事件上的会话ctrl,请帮忙,“panel1”中有一组文本框和标签。
      • 这个答案最好的部分是你可能会失去 ctrl
      • +1 失去控制我什至没有看到。为了设置会话变量,您必须在服务器端执行操作,例如您发布的 c# 代码。
      【解决方案3】:

      在aspx页面中创建方法

      <script type="text/javascript">
          function openPopUp()
          {
          window.open('Print.aspx','PrintMe','height=300px,width=300px,scrollbars=1');
          }
      </script>
      

      然后你在按钮上做

      <asp:Button ... onClientClick="openPopUp() onClick="btnClick"/>
      

      您可以同时拥有客户端事件和服务器端事件。

      protected void btnClick(object sender, EventArgs e)
          {
              Session["ctrl"] = Panel1;
          }
      

      【讨论】:

      • 谢谢尼克。我正在控制点击事件的会话变量。请帮忙。
      • 检查我的更新回复。你可以有两个事件。一个用于服务器端,一个用于客户端
      猜你喜欢
      • 2012-09-22
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-30
      • 1970-01-01
      相关资源
      最近更新 更多