向 html select 元素添加选项

Adding options to an html select element

我的 html 文件中有以下 select 元素:

<select id="usr-slct">
</select>

我正尝试在文档正文结尾之前的脚本标记中使用 javascript 添加一些选项。像这样:

var selector = document.getElementById("usr-slct");
var newoption = document.createElement("option").text="User1";
selector.add(newoption);

我想知道为什么此代码不能使我的页面显示 select 中的新选项,我怎样才能使其按预期工作?

document.createElement("option").text="User1"returns"User1",赋值的结果,不是HTMLOptionElement。你应该编码:

var newoption = document.createElement("option");
newoption.text = "User1";
selector.add(newoption);

edit:OP 正在使用 .add() 方法将 option 添加到 select 元素。 HTMLSelectElement object does have .add() method.

您的 select 元素有一个 'options' 属性,它是一个数组。您可以使用以下方法创建新选项:

selector.options[selector.options.length] = new Option('text1', 'value1');

这会在选择器选项数组的末尾添加一个新选项,文本为 text1,值为 value1,这将 return 您正在寻找的结果.

这里的问题是您正在这样做:

var newoption = document.createElement("option").text = "User1";

错了两次:

  • 首先在Javascript中赋值returns赋值,所以对新的文本属性赋值"User1"创建的选项导致您的变量保存字符串 "User1",而不是元素;您必须先创建元素,然后更改其文本。

  • 其次,你应该改变textContent 属性,而不是text 属性,这对[=]没有任何意义32=].

正确代码如下:

var selector = document.getElementById("usr-slct");
var newoption = document.createElement("option");

newoption.textContent = "User1";
selector.add(newoption);