简体   繁体   English

Javascript清除选择框的内容

[英]Javascript clear content of selectbox

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?为什么不从选择框中删除所有选项?

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 options changes when you iterate.您也可以一个一个地删除元素,就像您所做的那样,但是您必须考虑到迭代时options的长度会发生变化的事实。 The correct way to remove while iterating would have been迭代时删除的正确方法是

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

But the first solution is simpler of course.但第一个解决方案当然更简单。

var selectbox = document.getElementById(selectbox);

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

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

this example with new generation JavaScript.这个例子使用了新一代的 JavaScript。 I do recommend to use.我建议使用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM