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

时间:2017-01-31 16:52:42

标签: javascript html

为了保持简洁和简单,我有一个选择菜单,我不断追加并删除元素到选择下拉列表。我看了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]

enter image description here

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

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

select.length //12

enter image description here

真的很奇怪。这是它变得更加狡猾的地方。 如果我这样做......

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

IT STOPS at 12。

我不是在寻找这个问题的确切解决方案,但这是我过去几个小时一直在处理的绝对废话,如果有人可以指导我这个问题可能会发生在哪里它会救我一个很多压力:))

1 个答案:

答案 0 :(得分:2)

您可以尝试这种方式:

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);
}