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

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

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

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


当前回答

这是一种现代的纯JavaScript

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

其他回答

Try

document.getElementsByTagName("Option").length=0

或者可以查看removeChild()函数。

或者如果你使用jQuery框架。

$("DropList Option").each(function(){$(this).remove();});

这是一种现代的纯JavaScript

document.querySelectorAll('#selectId option').forEach(option => option.remove())
function removeOptions(obj) {
    while (obj.options.length) {
        obj.remove(0);
    }
}
var select = document.getElementById("DropList");
var length = select.options.length;
for (i = 0; i < length; i++) {
  select.options[i].remove();
}

希望,这段代码能帮到你

也许,这不是最干净的解决方案,但绝对比一个一个地移除简单:

document.getElementById("DropList").innerHTML = "";