javascript 无法删除选择菜单中的元素,

mcdcgff0  于 12个月前  发布在  Java
关注(0)|答案(2)|浏览(113)

为了保持简短,我有一个选择菜单,在那里我不断地向选择下拉列表添加和删除元素。我看了How do I clear all options in a dropdown box?Remove values from select list based on condition,但没有运气。我正在努力做这样的事情。

var select = document.getElementById('model-menu');

如果我这么做了...

select.options //returns an array [with a length of 24]

for (var i = 1; i <= select.options.length; i++) { 
    select.remove(i) 
}

现在的问题是。。只删除了一半

select.length //12

真的很奇怪这就是它变得更奇怪的地方。如果我做了...

for (var i = 0; i < select.options.length; i++) {
    console.log(i) //24 23 22 21....
}

它停在12。
我不是在寻找这个问题的确切解决方案,但这是我在过去几个小时里一直在处理的一些绝对的废话,如果有人能告诉我这个问题可能发生的地方,这将为我节省很多压力:)

8i9zcol2

8i9zcol21#

你可以试试这样:

function clearItems() {
  var select = document.getElementById("select1");
  for(i = select.options.length - 1 ; i >= 0 ; i--){
      select.remove(i);
  } 
}
<select id="select1">
  <option value="Item A">Item A</option>
  <option value="Item B">Item B</option>
  <option value="Item C">Item C</option>
  <option value="Item D">Item D</option>
</select>

<input type="button" value="Clear Items" onclick="clearItems()" />

这就是为什么你的代码不能正常工作的原因:
看看当你从开始循环到N时会发生什么:

for (var i = 0; i < select.options.length; i++) { 
  select.remove(i);
}

//initial length = 4 (0:A, 1:B, 2:C, 3:D)
//i=0  =>  remove(0)  =>  Item A will be removed
//now we have: 0:B, 1:C, 2:D  ,  length=3
//i=1  =>  remove(1)  =>  this will remove Item C (instead of Item B)
//now we have: 0:B, 1:D  ,  length=2  
//... so it will skip one item at each iteration!
//i=2  =>  (length=2) exit loop!
//... as length is decreasing at each loop 
//... and the loop stop condition will be evaluated at each iteration,
//... so we will stop at half of the loop!

//to solve this issue, we could also use this way:

var n1 = select.options.length; // cache the original length

for(i = 0 ; i < n1; i++){
  select.remove(0);
}
xu3bshqb

xu3bshqb2#

在我的例子中,我用一个反向循环解决了这个问题:

function removeOptions() {
  const arrayLength = selectElement.length - 1;
  for (let i = arrayLength; i > 0; i--) {
    selectElement.removeChild(selectElement[i]);
  }
}

相关问题