说我有以下代码:
DropDownList changesList = new DropDownList();
ListItem item;
item = new ListItem();
item.Text = "go to google.com";
changesList.Items.Add(item);
如何向item
动态添加OnClick事件,以便点击item
后访问google.com?
答案 0 :(得分:4)
将此添加到您的代码中:
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;");
答案 1 :(得分:0)
首先声明下拉列表
<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);
}
}
希望这有帮助