Javascript Javascript清除选择框的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13568194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:22:56  来源:igfitidea点击:

Javascript clear content of selectbox

javascript

提问by user197483

As part of my populating selectbox function I am clearing the contents of the populated select box and then inserting options to a empty box. Although the select box is not being cleared correctly and a lot of options are not removed. I am using the following code to clear the contents of the select box:

作为填充选择框功能的一部分,我正在清除填充选择框的内容,然后将选项插入一个空框。虽然选择框没有被正确清除,很多选项也没有被删除。我正在使用以下代码清除选择框的内容:

for(var i = 0; i < document.getElementById(selectbox).options.length; i++)
    document.getElementById(selectbox).options[i] = null;

Why not all the options are removed from the selectbox?

为什么不从选择框中删除所有选项?

回答by Denys Séguret

You can simply do

你可以简单地做

 document.getElementById(selectbox).options.length = 0;

You could also have removed the elements one by one, almost like you did, but you must take into account the fact the length of optionschanges when you iterate. The correct way to remove while iterating would have been

您也可以一个一个地删除元素,就像您所做的那样,但是您必须考虑options迭代时更改的长度这一事实。迭代时删除的正确方法是

for (var i=document.getElementById(selectbox).options.length; i-->0;)
    document.getElementById(selectbox).options[i] = null;

But the first solution is simpler of course.

但第一个解决方案当然更简单。

回答by Matt

var selectbox = document.getElementById(selectbox);

document.getElementById("emptyBox").innerHTML = selectbox.innerHTML;
selectbox.innerHTML = "";

回答by Metro Smurf

As an alternative and more terse method of clearing all options of a select list, we can take advantage of JavaScript's falsey value of zero and then simply remove the option from the Dom:

作为清除选择列表中所有选项的另一种更简洁的方法,我们可以利用 JavaScript 的 falsey 值为零,然后简单地从 Dom 中删除选项:

function clearSelectList(list) {
    // when length is 0, the evaluation will return false.
    while (list.options.length) {
        // continue to remove the first option until no options remain.
        list.remove(0);
    }
}

Usage would then be:

用法将是:

var list = document.getElementById("selectbox");
clearSelectList(list);

Or more succinctly:

或者更简洁:

clearSelectList(document.getElementById("selectbox"));

回答by Alperen Turkoz

this example with new generation JavaScript. I do recommend to use.

这个例子使用了新一代的 JavaScript。我建议使用。

[...cbrCenterSelectbox.options].forEach(option => option.remove())