我所做的是
var select = document.createElement("select");
var option1 = document.createElement("option");
var option2 = document.createElement("option");
select.appendChild(option);
select.appendChild(option);
// Set values and texts here.
option2.selected = true;
上面的代码的最后一行没有任何作用,我仍然得到option1
作为所选选项。我在这里想念什么?
答案 0 :(得分:0)
您需要将select
附加到正文中。它还有助于向option
添加一些文本:
var select = document.createElement("select");
var option1 = document.createElement("option");
var option2 = document.createElement("option");
var option3 = document.createElement("option");
document.body.appendChild(select);
option1.innerText = 'One';
option2.innerText = 'Two';
option3.innerText = 'Three';
select.appendChild(option1);
select.appendChild(option2);
select.appendChild(option3);
option2.selected = true;
我还添加了第三个选项,以表明option2.selected = true
被尊重
答案 1 :(得分:0)
将value
和innerHTML
属性添加到选择中。并解决错字
var select = document.createElement("select");
var option1 = document.createElement("option");
var option2 = document.createElement("option");
option1.value = "1";
option1.innerHTML = "1";
option2.value = "2";
option2.innerHTML = "2";
option2.selected = true;
select.appendChild(option1);
select.appendChild(option2);
document.getElementById('test').appendChild(select)
<div id='test'></div>
答案 2 :(得分:0)
您需要添加“ select [1] .selected = 1;”输入您的代码,请检查以下代码。这段代码对我有用。
var myDiv = document.getElementById("myDiv");
//Create array of options to be added
var array = ["Volvo","Saab","Mercades","Audi"];
//Create and append select list
var selectList = document.createElement("select");
selectList.setAttribute("id", "mySelect");
myDiv.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.setAttribute("value", array[i]);
option.text = array[i];
selectList.appendChild(option);
}
selectList[2].selected =1;