当试图从 select 中删除选项时,总是剩下一个,为什么?
<select id="form-select">
<option>111</option>
<option>222</option>
<option>333</option>
</select>
Run Code Online (Sandbox Code Playgroud)
这个 JS 不起作用:
var t = document.querySelector('#form-select');
for(var i of t.options) {
t.remove(i.index)
}
Run Code Online (Sandbox Code Playgroud)
这也不起作用:
for(var i of document.querySelector('#form-select').options) {
i.remove()
}
Run Code Online (Sandbox Code Playgroud)
我知道还有其他解决方案可以实现这一目标,但我想了解为什么它无法正常工作
该.options集合(不幸的是)是live,因此一个一个地迭代实时集合的项目并遍历.remove每个项目将导致每个奇数项目都被保留。(例如,当您删除第一个项目时,[0]集合的第 th 个项目将立即成为集合中的下一个项目 - 过去[1]将成为[0](然后一旦您转到下一个索引 at [1],位置的新项目0 不会被迭代)
使用document.querySelectorAll替代,它返回一个集合是静态的:
for (const option of document.querySelectorAll('#form-select > option')) {
option.remove();
}Run Code Online (Sandbox Code Playgroud)
<select id="form-select">
<option>111</option>
<option>222</option>
<option>333</option>
</select>Run Code Online (Sandbox Code Playgroud)
您还可以在删除元素之前扩展到(静态)数组中:
for (const option of [...document.querySelector('#form-select').options]) {
option.remove();
}Run Code Online (Sandbox Code Playgroud)
<select id="form-select">
<option>111</option>
<option>222</option>
<option>333</option>
</select>Run Code Online (Sandbox Code Playgroud)
另一个选项恰好可以工作,因为集合是实时的(但可能不应该使用,因为它不直观):
const { options } = document.querySelector('#form-select');
while (options.length) {
options[0].remove();
}Run Code Online (Sandbox Code Playgroud)
<select id="form-select">
<option>111</option>
<option>222</option>
<option>333</option>
</select>Run Code Online (Sandbox Code Playgroud)