我的代码可以在IE中运行,但在Safari、Firefox和Opera中会崩溃。(惊喜)

document.getElementById("DropList").options.length=0;

经过搜索,我了解到它不喜欢的是长度=0。 我试过了……选项=null和var clear=0...长度=clear,结果相同。

我一次对多个对象这样做,所以我正在寻找一些轻量级的JS代码。


当前回答

function removeOptions(obj) {
    while (obj.options.length) {
        obj.remove(0);
    }
}

其他回答

var select = document.getElementById('/*id attribute of your select here*/');
for (var option in select){
    select.remove(option);
}

使用JQuery是一种更漂亮、更短、更聪明的方法!

$('#selection_box_id').empty();

我想指出的是,最初问题中的问题在今天已经没有意义了。还有一个更简短的解决方案:

selectElement.length = 0;

我测试过,这两个版本都可以在Firefox 52、Chrome 49、Opera 36、Safari 5.1、IE 11、Edge 18、最新版本的Chrome、Firefox、三星互联网和UC浏览器(Android)、Safari (iPhone 6S)和Android 4.2.2常规浏览器上运行。我认为可以肯定地说,它与目前的任何设备都是完全兼容的,所以我推荐这种方法。

这是一种现代的纯JavaScript

document.querySelectorAll('#selectId option').forEach(option => option.remove())

要删除select的HTML元素的选项,可以使用remove()方法:

function removeOptions(selectElement) {
   var i, L = selectElement.options.length - 1;
   for(i = L; i >= 0; i--) {
      selectElement.remove(i);
   }
}

// using the function:
removeOptions(document.getElementById('DropList'));

重要的是要将选项向后移除;当remove()方法重新排列选项集合时。这样,就保证了要删除的元素仍然存在!