我的 html 文件中有以下选择元素:
<select id="usr-slct">
</select>
我正在尝试在文档正文末尾之前的脚本标记中使用 javascript 添加一些选项。像这样:
var selector = document.getElementById("usr-slct");
var newoption = document.createElement("option").text="User1";
selector.add(newoption);
我想知道为什么这段代码不能让我的页面在选择中显示新选项,我怎样才能让它按预期工作?
最佳答案
document.createElement("option").text="User1"
返回 "User1"
,赋值的结果,而不是 HTMLOptionElement
。你应该编码:
var newoption = document.createElement("option");
newoption.text = "User1";
selector.add(newoption);
编辑:OP 使用.add()
方法将option
添加到select
元素。 HTMLSelectElement
object does have .add()
method.
关于javascript - 向 html 选择元素添加选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29449828/