1

我在 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(不是在 javascript 中)中单击 div 时执行一些操作。

我尝试了以下

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 功能..这里有什么问题..

4

2 回答 2

4

这里

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接口。

于 2013-02-27T11:05:20.720 回答
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>

你可以在这里看到一些例子。

于 2013-02-27T11:00:36.727 回答