我想要完成的是使用 onClick 命令设置动态创建的链接按钮,以便在单击时它将运行后面代码中的方法。这是我的代码:
protected void Page_Init(object sender, EventArgs e)
{
LoadLeftSide();
}
private void LoadLeftSide()
{
string filepath = Server.MapPath("DataSource.xml");
List<Post> list = PostHelper.GetAllPosts(filepath);
HtmlTable table = FindControl("tbl") as HtmlTable;
HtmlTableRow hearderrow = new HtmlTableRow();
HtmlTableCell heardercell = new HtmlTableCell();
heardercell.InnerText = "Posts:";
hearderrow.Cells.Add(heardercell);
table.Rows.Add(hearderrow);
foreach (Post p in list)
{
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell cell1 = new HtmlTableCell();
LinkButton lnkPost = new LinkButton();
lnkPost.ID =string.Format("{0}" ,Guid.NewGuid());
lnkPost.Attributes.Add("runat", "server");
lnkPost.Text = p.Title;
// lnkPost.CommandName = p.Id.ToString();
// lnkPost.CommandArgument = p.Id.ToString();
//lnkPost.Command += new CommandEventHandler(this.onLinkClick);
lnkPost.Click += new EventHandler(this.onLinkClick);
cell1.Controls.Add(lnkPost);
row.Cells.Add(cell1);
table.Rows.Add(row);
}
table.DataBind();
}
protected void onLinkClick(object sender, EventArgs e)
{
string filepath = Server.MapPath("DataSource.xml");
int id = 1;
Post post=PostHelper.GetPostById(id, filepath);
lblDescription.Text = post.Description;
}
Run Code Online (Sandbox Code Playgroud)
Joh*_* K. -1
此示例添加一个按钮并将单击的功能设置为“删除”,这会在单击时删除新按钮...
function addNewButton() {
$("sweet_selector_here").append("<input type='button' id='sweetness' value='press me, i am awesome' />");
$("#sweetness").click(function() {
$(this).remove();
});
}
Run Code Online (Sandbox Code Playgroud)