我的一个应用程序中有下拉列表控件,当我从数据库中添加项目时,默认情况下它会将第一个项目显示到下拉列表中,但我想在其中显示其他文本,例如“从列表中选择项目”有什么办法我可以做这个 。
另外你能帮我从javascript设置相同的值吗
我的一个应用程序中有下拉列表控件,当我从数据库中添加项目时,默认情况下它会将第一个项目显示到下拉列表中,但我想在其中显示其他文本,例如“从列表中选择项目”有什么办法我可以做这个 。
另外你能帮我从javascript设置相同的值吗
在 ASP.NET 方面,您可以使用 AppendDataBoundItems="true" 创建 DropDownList ,并且您绑定到它的任何项目都将在默认值之后出现:
<asp:DropDownList AppendDataBoundItems="true" ID="yourListId" runat="server">
<asp:ListItem Text="Select something" Value="-1" />
</asp:DropDownList>
至于完全用 Javascript 做同样的事情,你可以用这样的函数来做:
function addFirstItem(list, text, value)
{
var newOption = document.createElement("option");
newOption.text = text;
newOption.value = value;
list.options.add(newOption);
}
addFirstItem(document.getElementById("yourListId"), "Select something", "-1");
或者使用 jQuery(可能有一些更清洁的东西,特别是对于创建新的选项标签,但这有效):
$("#yourListId option:first").before("<option value='-1'>Select something</option>");
Patridge 的回答是正确的,但是如果您使用 asp 方法并且仍然遇到问题,请将 items 标签添加到 listitem。
<asp:DropDownList AppendDataBoundItems="true" ID="yourListId" runat="server">
<items>
<asp:ListItem Text="Select something" Value="-1">--Select Something--</asp:ListItem>
</items>
</asp:DropDownList>