将javascript中的多个选择框动态添加到DOM [英] Adding multiple select boxes in javascript dynamically to DOM

查看:30
本文介绍了将javascript中的多个选择框动态添加到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 对象并在第一个和第二个选择框中插入选项时,只有第二个选择框被填充,第一个为空.我必须拿两个选项对象.为什么呢?这不是问题,但我想了解为什么会这样.

When I use op object and insert the option in the 1st and 2nd select box, only the 2nd select box is populated and 1st one is empty. I've to take two option objects. Why is that so? It's not a problem but I want to understand why it's happening.

推荐答案

如果你selectBox1.options.add(op) 你需要知道什么 你会添加 op 到 selectBox1 选项然后当你这样做时selectBox2.options.add(op) 它将从 selectBox1 选项中删除它并将其添加到 selectBox2 选项中.

What you need to know if you selectBox1.options.add(op) you will add op to selectBox1 options then when you do selectBox2.options.add(op) it will remove it from selectBox1 options and add it to selectBox2 options.

使用那个op1

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

这篇关于将javascript中的多个选择框动态添加到DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆