[英]Can't remove elements in a select menu.
to keep this short and simple, I have a select menu where I am constantly appending and removing elements to a select dropdown. 为简短起见,我有一个选择菜单,在该菜单中,我不断向选择下拉列表中添加和删除元素。 I looked at How do I clear all options in a dropdown box?
我查看了如何清除下拉框中的所有选项? and Remove values from select list based on condition but had no luck.
并根据条件从选择列表中删除值,但没有运气。 I am trying to do something like this.
我正在尝试做这样的事情。
var select = document.getElementById('model-menu');
Now if I do... 现在如果...
select.options //returns an array [with a length of 24]
for (var i = 1; i <= select.options.length; i++) {
select.remove(i)
}
The problem now is that... it only removed half. 现在的问题是... 它只去除了一半。
select.length //12
It's really wierd. 真的很奇怪 This is where it gets even wierder.
这就是它变得更加奇怪的地方。 If I do...
如果我做...
for (var i = 0; i < select.options.length; i++) {
console.log(i) //24 23 22 21....
}
IT STOPS AT 12. 它停在12。
I am not looking for an exact solution to this problem, but this is some absolute nonsense that I have been dealing with for the past few hours and If someone can direct me to where this issue MIGHT be happening it will save me a lot of stress :) 我没有在寻找解决此问题的确切方法,但这是我过去几个小时一直在处理的胡说八道,如果有人可以将我定向到可能发生此问题的地方,它将为我节省很多压力:)
You can try this way: 您可以这样尝试:
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()" />
And this is why you code not works properly: 这就是为什么您的代码无法正常工作的原因:
see what happens when you loop from beginning to N as: 看看当您从开头循环到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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.