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

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

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

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


当前回答

这是一条很短的路:

document.getElementById('mySelect').innerText = null;

一行,没有for,没有JQuery,很简单。

其他回答

如果您希望使用轻量级脚本,那么请使用jQuery。 在jQuery中,删除所有选项的解决方案如下:

$("#droplist").empty();

要删除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()方法重新排列选项集合时。这样,就保证了要删除的元素仍然存在!

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

使用PrototypeJS:

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