动态创建的div不可点击C#ASP.NET

时间:2016-07-23 02:27:31

标签: c# html asp.net

基本上我是根据数字创建div。这是我创建这些div的地方:

cssStyle.Attributes["href"]="Content/Options/"+(Global.NumberOfResponses).ToString() +".css";
string x = "<table class=\"Centralizetable\"><tr>";
for (int i = 0; i < Global.NumberOfResponses; i++) { 
    if(i==0){
        x = x + "<td><div class=\"leftmost\" onClick=\"myClickListener\" runat=\"server\"><img class=\"imageProps\" src=\"/Images/1.jpg\" id=\"imgChoice_" + i.ToString()+ "\" /><p class=\"optionText\">Good</p></div></td>";
    }
    else {
        x = x + "<td><div class=\"center\"  onClick=\"myClickListener\" runat=\"server\"><img class=\"imageProps\" src=\"/Images/1.jpg\" id=\"imgChoice_" + i.ToString() + "\" /><p class=\"optionText\">Good</p></div></td>";
    }
}

x = x + "</tr></table>";

multichoice.InnerHtml = x;

它应该调用这个函数:

public void myClickListener(object sender, EventArgs e)
{
    Image A = sender as Image;
    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('"+A.ID+"')", true);
}

但动态创建的div不可点击。

2 个答案:

答案 0 :(得分:0)

您应该尝试OnServerClick而不是onClick

cssStyle.Attributes["href"]="Content/Options/"+(Global.NumberOfResponses).ToString() +".css";
string x = "<table class=\"Centralizetable\"><tr>";
for (int i = 0; i < Global.NumberOfResponses; i++) { 
    if(i==0){
        x = x + "<td><div class=\"leftmost\" OnServerClick=\"myClickListener\" runat=\"server\"><img class=\"imageProps\" src=\"/Images/1.jpg\" id=\"imgChoice_" + i.ToString()+ "\" /><p class=\"optionText\">Good</p></div></td>";
    }
    else {
        x = x + "<td><div class=\"center\"  OnServerClick=\"myClickListener\" runat=\"server\"><img class=\"imageProps\" src=\"/Images/1.jpg\" id=\"imgChoice_" + i.ToString() + "\" /><p class=\"optionText\">Good</p></div></td>";
    }
}

x = x + "</tr></table>";

multichoice.InnerHtml = x;

有关更多信息,请参阅MSDNSO

答案 1 :(得分:0)

如果查看呈现的HTML,您应该看到正在呈现[runat =&#34; Server&#34;]属性。您正在创建动态HTML,但它不作为服务器端控件处理。

如果需要调用服务器调用,可以更改click事件以调用JavaScript函数或更改它们创建元素的方式

请参阅MSDN了解how to programmatically adding controls