【问题标题】:Click event on div in asp.net在 asp.net 中的 div 上单击事件
【发布时间】:2013-02-27 10:55:21
【问题描述】:

我在 default.aspx 中有一个 div,里面有 img 如下

 <div id="sTab" class="tabs firsttab" runat="server">
     <asp:Image ID="sTabImg"  src="images/home.png" runat="server" />
 Activities
</div>

我想在点击 ASP.NET 中的 div 时执行一些操作(不是在 javascript 中)。

我尝试了以下

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
    }

    sTabImg.Attributes["onclick"] = ClientScript.GetPostBackEventReference(this, "ClickDiv");
}

protected void ClickDiv()
{
    Label2.Text = "helo got it";
}

页面正在刷新,当我调试问题时,它没有进入 ClickDiv 函数..这里有什么问题..

【问题讨论】:

  • div的onclick事件是客户端事件。所以使用ImageButton之类的服务器控件而不是Image并引发事件..

标签: asp.net .net


【解决方案1】:

来自Here

public partial class _Default : System.Web.UI.Page, IPostBackEventHandler
{

    protected void Page_Load(object sender, EventArgs e)
    {
       div1.Attributes["onclick"]=ClientScript.GetPostBackEventReference(this,"ClickDiv");
    }

    protected void Div1_Click()
    {
      // Do something
    }

    #region IPostBackEventHandler Members

    public void RaisePostBackEvent(string eventArgument)
    {

      if (!string.IsNullOrEmpty(eventArgument))
      {

              if (eventArgument == "ClickDiv")
              {
                 Div1_Click();
              }
      }
    }

    #endregion
}

您必须实现 IPostBackEventHandler 接口。

【讨论】:

    【解决方案2】:

    为什么不使用ImageButton

    <%@ Page Language="C#" AutoEventWireup="True" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title>ImageButton Sample</title>
    <script language="C#" runat="server">
    
          void ImageButton_Click(object sender, ImageClickEventArgs e) 
          {
             Label1.Text = "You clicked the ImageButton control at the coordinates: (" + 
                           e.X.ToString() + ", " + e.Y.ToString() + ")";
          }
    
    </script>
    
    </head>
    <body>
    <form id="form1" runat="server">
    
      <h3>ImageButton Sample</h3>
    
      Click anywhere on the image.<br /><br />
    
      <asp:ImageButton id="imagebutton1" runat="server"
           AlternateText="ImageButton 1"
           ImageAlign="left"
           ImageUrl="images/pict.jpg"
           OnClick="ImageButton_Click"/>
    
          <br /><br />
    
          <asp:label id="Label1" runat="server"/>
    
       </form>
    
    </body>
    </html>
    

    你可以看到一些例子here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      相关资源
      最近更新 更多