我有两个空的选择字段,我想在某个数组上迭代一次,在每次迭代中创建一个选项元素,并将其附加到两个选择字段.问题是只有最后一个元素获得选项,第一个元素保持为空:
HTML
<select class="form-control" id="typeCol">
</select>
<br>
<select class="form-control" id="diffCol">
</select>
Run Code Online (Sandbox Code Playgroud)
JavaScript的
let typeCol = document.getElementById('typeCol');
let diffCol = document.getElementById('diffCol');
for (let i in cols) {
let opt = document.createElement('option');
opt.value = i;
opt.innerHTML = cols[i];
typeCol.appendChild(opt);
diffCol.appendChild(opt);
}
Run Code Online (Sandbox Code Playgroud)
添加另一个for
循环并附加到第二个循环select
似乎工作,但仍然 - 发生了什么?
元素只能在一个父元素内.如果您appendChild
在已经拥有父元素的元素上使用它,则它将从旧父元素移动到新父元素.
您可以使用它cloneNode
来创建元素的克隆:
diffCol.appendChild(opt.cloneNode(true));
Run Code Online (Sandbox Code Playgroud)
例:
let typeCol = document.getElementById('typeCol');
let diffCol = document.getElementById('diffCol');
let cols = ["one", "two", "three"];
for (let i in cols) {
let opt = document.createElement('option');
opt.value = i;
opt.innerHTML = cols[i];
typeCol.appendChild(opt);
diffCol.appendChild(opt.cloneNode(true));
}
Run Code Online (Sandbox Code Playgroud)
<select class="form-control" id="typeCol">
</select>
<br>
<select class="form-control" id="diffCol">
</select>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
62 次 |
最近记录: |