在 Javascript 中动态创建选项元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16144415/
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
Dynamically create option elements in Javascript
提问by GOTO 0
What is the preferred way in Javascript to dynamically create DOM option elements? I've found both the Option constructor and the createElement variant used in actual code like this:
Javascript 中动态创建 DOM 选项元素的首选方法是什么?我发现在实际代码中使用了 Option 构造函数和 createElement 变体,如下所示:
var option = new Option(text, value);
and this:
还有这个:
var option = document.createElement('option');
option.text = text;
option.value = value;
Are there any drawbacks/compatibility issues with any of those methods? Also, are there any other methods to create options dynamically that should be preferred to the above for some reasons?
这些方法是否有任何缺点/兼容性问题?此外,是否有任何其他方法可以动态创建选项,出于某些原因应该优先于上述方法?
采纳答案by MaxArt
There are no differences between the two methods that I know of. Using the Option
constructor allows you to conveniently set the value and the text of the option, but you can do the same using the value
and text
properties.
我所知道的这两种方法之间没有区别。使用Option
构造函数可以方便地设置选项的值和文本,但您可以使用value
和text
属性来做同样的事情。
There could have been the innerHTML
way, but IE8 and older fail hard on this...
本来是有innerHTML
办法的,但是 IE8 和更早的版本在这方面很难做到......
回答by goe
I noticed for example that using new Option() doesn't work well under IE9 where it works in IE10 and IE11. I recently had go back to the original code and revert the change somebody did to go back using document.createElement('option') in order for IE9 to work.
例如,我注意到在 IE9 下使用 new Option() 不能很好地工作,而它在 IE10 和 IE11 中工作。我最近回到了原始代码并恢复了某人使用 document.createElement('option') 返回的更改,以便 IE9 工作。