selectBox1 = document.createElement("select");
selectBox2 = document.createElement("select");
selectBox1.setAttribute("id","select1");
selectBox2.setAttribute("id","select2");
tr = document.createElement('tr');
for(var k = 1; k<headers.length; k++){
var op = new Option();
var op1 = new Option();
op.value = op1.value= headers[k];
op.text = op1.text = headers[k];
selectBox1.options.add(op);
selectBox2.options.add(op);
th = document.createElement('th');
th.appendChild(document.createTextNode(headers[k]));
tr.appendChild(th);
}
document.getElementById("table").appendChild(selectBox1);
document.getElementById("table").appendChild(selectBox2);
当我使用 op 对象并将选项插入第一个和第二个选择框中时,只有第二个选择框被填充,第一个选择框为空。我必须采取两个选项对象。为什么会这样?这不是问题,但我想了解为什么会发生这种情况。
最佳答案
如果您 selectBox1.options.add(op) 将 op 添加到 selectBox1 选项,那么当您执行 selectBox2.options.add(op) 时,您需要了解什么> 它将从 selectBox1 选项中删除它并将其添加到 selectBox2 选项中。
使用op1
selectBox1.options.add(op1);
selectBox2.options.add(op);
关于javascript - 将javascript中的多个选择框动态添加到DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31849048/