使用 Prototype 库使用 javascript 向 Select 元素添加选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2139668/
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
Adding an Option to a Select Element with javascript using the Prototype library
提问by jamesmhaley
Want a to add an option dynamically to an Select element using prototype.
想要使用原型将选项动态添加到 Select 元素。
There seems to be a lot of different ways to do it out there, all to do with options.add etc... Not seen much in the way of cross-browser ways.
似乎有很多不同的方法可以做到这一点,所有这些都与 options.add 等有关......跨浏览器的方式很少见。
Want it to be as light-weight as possible.
希望它尽可能轻巧。
This is what I have got so far. It's just the appending the options that i'm stuck on:
这是我到目前为止所得到的。这只是附加我坚持的选项:
var oNewOption = new Element('option').value=vItem;
oNewOption.text=vItem;
Any ideas anyone?
任何人的想法?
Thanks in advance!
提前致谢!
回答by Tim Down
No need for Prototype, it'll be just as easy with the following time-honoured method that works in every major desktop browser since the mid-1990s:
不需要 Prototype,使用以下自 1990 年代中期以来适用于每个主要桌面浏览器的历史悠久的方法将同样简单:
// Assuming a select element stored in a variable called 'select'
select.options[select.options.length] = new Option("Option text", "optionValue");
回答by Alsciende
select.insert(new Element('option', {value: myValue}).update(myLabel));
insertappends to the content of the selectobject, updateupdates the content of the new option object.
insert附加到select对象的内容,update更新新选项对象的内容。
Not really better than the classic way, though.
不过,并不比经典方式更好。

