【问题标题】:add mouseclick event to panel将鼠标点击事件添加到面板
【发布时间】:2012-09-26 05:45:01
【问题描述】:

我想将mouseclick 事件分配给asp.net panel

protected void Page_Load(object sender, EventArgs e)
{
    Panel p = new Panel();
    p.Click += new EventHandler(b_Click);//but, this doesn't compiles correctly
}
protected void b_Click(object sender, EventArgs e) 
{
     //C#code
}

有没有办法给面板添加点击事件?

【问题讨论】:

标签: c# asp.net panel mouseclick-event


【解决方案1】:

您可以执行以下操作以使您的面板可点击并在服务器端处理事件。

在您的网络表单中放置面板

<asp:Panel runat="server" ClientIDMode="Static" ID="clickMe">
    Click here
</asp:Panel>

将 jQuery 脚本库添加到您的页面。

<script src="http://code.jquery.com/jquery.min.js" language="javascript"
        type="text/javascript"></script>

定义以下客户端事件处理程序

$(document).ready(function() {
    $("#clickMe").click(function () {
        __doPostBack('clickMe', '');
    });
});

在服务器端处理事件。

protected void Page_PreRender(object sender, EventArgs e)
{
    this.Page.ClientScript.GetPostBackEventReference(clickMe, "");
}

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Form["__EVENTTARGET"] == "clickMe")
    {
        ClickMeOnClick();
    }
}

PreRender 事件处理程序中的代码是供asp.net 框架在客户端渲染__doPostBack 函数。如果您的页面包含导致自动回发的控件,则不需要此代码。

【讨论】:

    【解决方案2】:

    使用 jQuery 1.7 的鼠标点击事件:

    $('#placeholderID').on('click', '#panelID', function(e){ });
    

    【讨论】:

      【解决方案3】:

      如果您想要更简单的解决方案,请在面板结束标记之前放置一个按钮,制作,设置 css 样式以覆盖整个面板和 opacity:0,调整 z-index 以不覆盖您的其他元素,然后使用后面代码中的 onclick 方法。

      示例:

      css:

      btn-panel{
          position: fixed;
          top: 0px;
          left: 0px;
          width: 100%;
          height: 100%;
          opacity: 0;
          z-index: -1;
      }
      

      asp:

      <asp:Panel ID="myPanel" runat="server" >
      
                  //all your other elements here...
                  <asp:Button ID="Button1" runat="server" Text="" CssClass="btn-panel"
                      OnClick="YourButton_Click" />
      </asp:Panel>
      

      后面的代码:

      protected void YourButton_Click(object sender, EventArgs e)
          {
             // Your Code Here...
          }
      

      你去吧,没有 javascript 也没有 jquery 来做魔术!

      【讨论】:

        【解决方案4】:

        asp:Panel 更改为asp:LinkButton 或将面板包裹在LinkBut​​ton 中。这也可以防止 OnClick 与子控件单击发生冲突,例如 asp:CheckBox

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-11
          • 1970-01-01
          相关资源
          最近更新 更多