如何使用 jQuery 向下拉列表添加选项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7997209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:34:49  来源:igfitidea点击:

How do I add an option to a dropdown list using jQuery?

jqueryasp.netwebforms

提问by DenaliHardtail

I'm trying to use the following code to add an option to a dropdown list in ASP.NET. Any ideas why this doesn't work? I tried Googling but can't figure out why this won't work.

我正在尝试使用以下代码向 ASP.NET 中的下拉列表添加一个选项。任何想法为什么这不起作用?我试过谷歌搜索,但不知道为什么这不起作用。

What shoud the code do? I have an ASP.NET dropdown list. I want to access the dropdown list by name and add an item to the list. The item should have descriptive text of "Some Text" and a value of "123".

代码应该做什么?我有一个 ASP.NET 下拉列表。我想按名称访问下拉列表并向列表中添加一个项目。该项目应具有“Some Text”的描述性文本和“123”的值。

Thanks!

谢谢!

$("#ddlCategory").append($("<option>Some Text</option>").val(1).html("123"));

采纳答案by Mark Schultheiss

var newOption = "<option value='"+"1"+"'>Some Text</option>"; 
$("#ddlCategory").append(newOption);

回答by Jason

You can try

你可以试试

$("#ddlCategory").append($("<option value='123'>Some Text</option>");

Or

或者

 $('#ddlCategory').
      append($("<option></option>").
      attr("value", "123").
      text("Some Text")); 

2nd code snippet from this question What is the best way to add options to a select from an array with jQuery?

来自这个问题的第二个代码片段什么是使用 jQuery 从数组中选择添加选项的最佳方法?

回答by user369142

Have you tested that 1) your jquery is correct and works in a flat HTML file and 2) that you are using the correct Id - ASP.NET changes Ids dynamically on elements that runat="server", so you might want to try:

您是否测试过 1)您的 jquery 是正确的并且可以在平面 HTML 文件中工作,以及 2)您使用的是正确的 Id - ASP.NET 在 runat="server" 的元素上动态更改 Id,因此您可能想尝试:

$('#<%=ddlCategory.ClientID%>').append(...etc etc

That will get you the correct Id from the ASP.NET page class.

这将从 ASP.NET 页面类中获得正确的 Id。

回答by Milan Jaric

What if you change it to

如果你把它改成

$("#ddlCategory").append($("<option></option>").attr("value", "1").text("Some Text"));

回答by arb

Trying to add options to an ASP.Net dropdown list with client-side code is a bad idea. It introduces all sorts of postback problems. See this linkfor more details. You should either populate the dropdown completely client side, or trigger a partial postback to fill the list.

尝试使用客户端代码向 ASP.Net 下拉列表添加选项是一个坏主意。它引入了各种回发问题。有关更多详细信息,请参阅此链接。您应该在客户端完全填充下拉列表,或者触发部分回发以填充列表。