Javascript 使用innerHTML(JS)插入select元素
我正在尝试将Javascript 使用innerHTML(JS)插入select元素,javascript,html,select,innerhtml,Javascript,Html,Select,Innerhtml,我正在尝试将td标记中的内容替换为id“row2” 有人能告诉我为什么innerHTML行不起作用吗 var e = document.getElementById("location"); //location is the <select> ID var area = e.options.selectedIndex; if (area == 1) { var myRow = document.getElementById("row1"); var array =
td
标记中的内容替换为id“row2”
有人能告诉我为什么innerHTML
行不起作用吗
var e = document.getElementById("location"); //location is the <select> ID
var area = e.options.selectedIndex;
if (area == 1) {
var myRow = document.getElementById("row1");
var array = ["item1", "item2", "item3"];
var selectList = document.createElement("select");
selectList.setAttribute("id", "mySelect");
document.getElementById("row2").innerHTML = selectList
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);
}
}
var e=document.getElementById(“位置”)//位置是ID
var区域=e.options.selectedIndex;
如果(面积=1){
var myRow=document.getElementById(“行1”);
变量数组=[“项1”、“项2”、“项3”];
var selectList=document.createElement(“选择”);
setAttribute(“id”、“mySelect”);
document.getElementById(“row2”).innerHTML=selectList
对于(var i=0;i
选择列表
不是HTML字符串。您必须像使用选项那样使用appendChild
改变
document.getElementById("row2").innerHTML = selectList;
至
document.getElementById("row2").innerHTML = "";
document.getElementById("row2").appendChild(selectList);
innerHTML=”“应避免重复。
请参阅JSFiddle上的一个工作示例:您需要使用appendChild
将新元素作为元素的子元素插入
innerHTML
是元素中的HTML文本,不应为其分配元素
只需这样做:
document.getElementById("row2").appendChild(selectList);
通过将innerHTML
设置为”
,您可以在附加子项之前清除它,但它将计为对DOM的两次更新,浏览器可能会重新绘制或重新计算页面两次,而不是一次
更好的解决方案是使用replaceChild
方法,在单个步骤中替换子项:
var row2 = document.getElementById("row2");
if (row2.childNodes.length > 0) {
/* there is already a child attached to the element, so replace it */
row2.replaceChild(selectList, row2.childNodes.item(0));
} else {
/* there is no child attached to the element, append it */
row2.appendChild(selectList);
}
这些函数是W3C记录的节点
接口的一部分,请查看:document.createElement
创建对象,而不是字符串。您应该使用appendChild
而不是innerHTML
来添加它,这是我首先做的。但是我有一个if语句,它选择应该将几个可能的selectlist添加到HTML中。将.appendChild与此if语句一起使用时,如果用户改变主意并再次单击相同的选项,则会创建重复项。换句话说,我希望避免重复。appendChild创建。一个简单的解决方案是在追加子项之前清空第2行html