javascript - 将javascript中的多个选择框动态添加到DOM

标签 javascript html dom

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 选项中。

enter image description here

使用op1

selectBox1.options.add(op1);
selectBox2.options.add(op); 

关于javascript - 将javascript中的多个选择框动态添加到DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31849048/

相关文章:

javascript - 从关联数组/对象中提取的全局变量?

javascript - 如何将 JavaScript 对象/数组发送到前端 - node.js 应用程序

java - 使用 Java DOM 解析器对 XML 输出进行标记 - 多个子节点值

javascript - 使用 agm 库在 Angular 2 中创建多边形

javascript - 在后台播放音频 (Windows 8)

javascript - 将 jQuery 选择保存到变量的行为不同

css - 调整背景图像大小以适合 div

html - 在我的案例中奇怪的 ul 列表问题

javascript - Chrome 窗口不会从无限滚动加载内容,除非窗口(选项卡)处于焦点状态

javascript - 从字符串创建一个 JavaScript 对象