使用 javascript 填充 ASP.NET 下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8458594/
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
populate ASP.NET dropdownlist using javascript
提问by Ali_dotNet
how can I populate an ASP.NET dropdownlist using javascript? also how can I clear all dropdownlist items?
如何使用 javascript 填充 ASP.NET 下拉列表?也如何清除所有下拉列表项?
thanks
谢谢
回答by Darin Dimitrov
how can I populate an ASP.NET dropdownlist using javascript?
如何使用 javascript 填充 ASP.NET 下拉列表?
javascript knows nothing about server side language. All it sees is client side HTML. Javascript could be used to manipulate the DOM. How this DOM was generated is not important. So when you talk about ASP.NET dropdownlist, what it actually means to a javascript function is a client side HTML <select>
element.
javascript 对服务器端语言一无所知。它看到的只是客户端 HTML。Javascript 可用于操作 DOM。这个 DOM 是如何生成的并不重要。因此,当您谈论 ASP.NET 下拉列表时,它对 javascript 函数的实际含义是客户端 HTML<select>
元素。
Assuming this element has a corresponding unique id, you could add <option>
to it:
假设这个元素有一个对应的唯一 id,你可以添加<option>
到它:
var select = document.getElementById('<%= SomeDdl.ClientID %>');
var option = document.createElement("option");
option.value = '1';
option.innerHTML = 'item 1';
select.appendChild(option);
Notice how <%= SomeDdl.ClientID %>
is used to retrieve the client id of the dropdown list generated by ASP.NET. This will only work if the javascript is inline. If you use this in a separate javascript file you will have to define some global variable pointing to the id of the dropdown list or simply use deterministic ids if you are using ASP.NET 4.0.
请注意如何<%= SomeDdl.ClientID %>
用于检索 ASP.NET 生成的下拉列表的客户端 ID。这仅在 javascript 内联时才有效。如果您在单独的 javascript 文件中使用它,则必须定义一些指向下拉列表 ID 的全局变量,或者如果您使用的是 ASP.NET 4.0,则只需使用确定性 ID。
Here's a live demo.
这是一个现场演示。
also how can I clear all dropdownlist items?
也如何清除所有下拉列表项?
You could set the length of the corresponding <select>
to 0:
您可以将对应的长度设置<select>
为 0:
document.getElementById('<%= SomeDdl.ClientID %>').length = 0;
And a live demo.
和现场演示。