據我所知,有兩種方法可以完成您要做的事情。請使用asp:ImageButton
服務器控件,並使用OnItemDataBound
事件連接onclick
客戶端事件,或者直接使用<input type="image" />
控件並以內聯方式連接ClientID
。下面的示例顯示了這兩種方法:
<%@ 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 runat="server"><title>OnClick Test</title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListView ID="lv1" OnItemDataBound="lv1_ItemDataBound" runat="server">
<ItemTemplate>
<asp:Label ID="label1" Text="<%# Container.DataItem %>" runat="server" />
<asp:ImageButton ID="btn1"
ImageUrl="myimage.jpg"
AlternateText="Show Text"
runat="server" />
<input type="image" src="myimage.jpg" alt="Show Text"
onclick="alert(document.getElementById('<%# Container.FindControl("label1").ClientID %>').innerText);"
/>
<br />
</ItemTemplate>
</asp:ListView>
</div>
</form>
</body>
</html>
<script runat="server">
public void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) return;
lv1.DataSource = new[] {"Manny", "Moe", "Jack"};
lv1.DataBind();
}
protected void lv1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
var label1 = e.Item.FindControl("label1") as Label;
var btn1 = e.Item.FindControl("btn1") as ImageButton;
if (label1 == null || btn1 == null) return;
btn1.Attributes.Add("onclick", "alert(document.getElementById('" + label1.ClientID + "').innerText);");
}
</script>
標籤應標註 – dugas 2012-01-18 23:32:25
也許是這樣,但它並沒有幫助... – Gio 2012-01-18 23:34:45
嘗試#<%= Control.ClientID%>和錯誤定義,如果你不給任何每個屬性之間的空間會給你帶來錯誤。 – coder 2012-01-18 23:40:53