为何option元素仅添加到最后一个select标签,而非全部?
为何仅最后一个select标签生成了option?
核心原因很简单:DOM节点是唯一的,同一个option元素不能同时属于两个不同的父元素。
当你用appendChild()把同一个option节点添加到第二个select时,浏览器会自动把这个节点从第一个select的DOM树中移除,再放到第二个select里——因为一个DOM元素在页面中只能有一个“位置”,重复添加本质是“移动”操作,而非“复制”。
举个你大概率会写的错误代码示例:
const selects = document.querySelectorAll('.droplistOptions'); const countryNames = ['中国', '美国', '英国']; countryNames.forEach(name => { const option = document.createElement('option'); option.textContent = name; selects[0].appendChild(option); // 这里不是新增,是把option从第一个select移到第二个 selects[1].appendChild(option); });
每次循环里的option是同一个DOM对象,第一次append到第一个select,第二次append就会把它移走,循环结束后所有option自然都跑到最后一个select里了,第一个select就空了。
解决办法
有两种常见的修复方式:
- 为每个select单独创建独立的option元素
const selects = document.querySelectorAll('.droplistOptions'); const countryNames = ['中国', '美国', '英国']; countryNames.forEach(name => { // 给第一个select创建专属option const opt1 = document.createElement('option'); opt1.textContent = name; selects[0].appendChild(opt1); // 给第二个select创建独立的option const opt2 = document.createElement('option'); opt2.textContent = name; selects[1].appendChild(opt2); });
- 用
cloneNode(true)克隆已创建的option节点
const selects = document.querySelectorAll('.droplistOptions'); const countryNames = ['中国', '美国', '英国']; countryNames.forEach(name => { const option = document.createElement('option'); option.textContent = name; selects[0].appendChild(option); // 克隆一个包含内容的新节点,添加到第二个select selects[1].appendChild(option.cloneNode(true)); });
内容的提问来源于stack exchange,提问作者dhairyash
相关产品推荐
相关产品推荐

