问问题
279 次
1 回答
3
问题是,当您克隆一个节点时,您实际上是使用它的 HTML 标记并从该标记中创建一个新元素。选定<option>
对象的任何 HTML 属性都不会因被选定而更改,除非您明确地这样做(通过为选定对象<option>
提供一个selected
属性,并确保没有其他<option>
标签具有该属性)。
const origSelect = document.querySelector('select');
const options = [...origSelect.options];
origSelect.addEventListener('change', () => {
options.forEach(option => option.removeAttribute('selected'));
options[origSelect.selectedIndex].setAttribute('selected', '');
});
function cloneIt() {
let newFields = document.getElementById('clonedFields');
let cloneThis = document.getElementById('cloneThis');
let clonedNode = cloneThis.cloneNode(true);
clonedNode.querySelector('select').value = origSelect.value;
newFields.parentNode.appendChild(clonedNode);
}
<div id="cloneParent">
<div id="cloneThis">
<select id="cloneTestSelect">
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
<option value="Option3">Option3</option>
<option value="Option4">Option4</option>
</select>
<label for="cloneTestText">Text Input: </label>
<input type="text" id="cloneTestText">
<label for="cloneTestNumber">Number Input: </label>
<input type="text" id="cloneTestNum">
</div>
</div>
<br>
<h1>Cloned fields: </h1>
<br>
<div id="clonedFields"></div>
<button onclick="cloneIt()">Clone inputs</button>
虽然您可以这样做,但简单地检索 的当前值<select>
并将新的选择标签设置为原始选择的值会更容易:
const origSelect = document.querySelector('select');
function cloneIt() {
let newFields = document.getElementById('clonedFields');
let cloneThis = document.getElementById('cloneThis');
let clonedNode = cloneThis.cloneNode(true);
clonedNode.querySelector('select').value = origSelect.value;
newFields.parentNode.appendChild(clonedNode);
}
<div id="cloneParent">
<div id="cloneThis">
<select id="cloneTestSelect">
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
<option value="Option3">Option3</option>
<option value="Option4">Option4</option>
</select>
<label for="cloneTestText">Text Input: </label>
<input type="text" id="cloneTestText">
<label for="cloneTestNumber">Number Input: </label>
<input type="text" id="cloneTestNum">
</div>
</div>
<br>
<h1>Cloned fields: </h1>
<br>
<div id="clonedFields"></div>
<button onclick="cloneIt()">Clone inputs</button>
于 2019-08-10T22:26:29.977 回答