如何在动态添加的DropDownList's ListItem上添加OnClick事件
本文关键字:添加 ListItem 事件 OnClick 动态 DropDownList | 更新日期: 2023-09-27 18:09:37
假设我有以下代码:
DropDownList changesList = new DropDownList();
ListItem item;
item = new ListItem();
item.Text = "go to google.com";
changesList.Items.Add(item);
如何动态添加OnClick事件到item
,以便点击item
后google.com将被访问
将此添加到您的代码中:
DropDownList changesList = new DropDownList();
ListItem item;
item = new ListItem();
item.Text = "go to google.com";
item.Value = "http://www.google.com";
changesList.Items.Add(item);
changesList.Attributes.Add("onChange", "location.href = this.options[this.selectedIndex].value;");
首先声明下拉列表
<asp:DropDownList ID="ddlDestination" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddl_SelectedIndexChanged">
<asp:ListItem Text="Select Destination" Selected="True" />
<asp:ListItem Text="Go To Google.com" Value="http://www.google.com" />
<asp:ListItem Text="Go To Yahoo.com" Value="http://www.yahoo.com" />
<asp:ListItem Text="Go To stackoverflow.com" Value="http://www.stackoverflow.com" />
</asp:DropDownList>
第二,在后面的代码中放入这段代码
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlDestination.SelectedIndex > 0)
{
string goToWebsite = ddlDestination.SelectedValue;
Response.Redirect(goToWebsite);
}
}
希望能有所帮助