【问题标题】:Can't remove elements in a select menu.无法删除选择菜单中的元素。
【发布时间】:2017-01-31 16:52:41
【问题描述】:

为了保持简短和简单,我有一个选择菜单,我不断地在选择下拉菜单中添加和删除元素。我看了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 点停止。

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

【问题讨论】:

  • 您正在从您迭代的集合中删除,这是您的问题;)。
  • 如果你想把它们全部删除。看看这个问题:How do I empty an array in JavaScript?
  • @xszaboj 相信我,我尝试将它设置为一个空数组,但没有成功。这可能是因为 select 是静态的......不是动态的。我现在要阅读 Nodelists
  • 你试过$(select.options).clear() 吗?...而不是一一迭代?

标签: javascript html


【解决方案1】:

你可以试试这个方法:

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

【讨论】:

  • 是的!我来这里是为了回答我自己的问题,但你为我做了这件事 Reactiflux 社区中的某个人解释说这是一个 NodeList 问题,如果我按照我的方式迭代它,我就会越界。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-04
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 2017-05-03
相关资源
最近更新 更多