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

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

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

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


当前回答

对于Vanilla JavaScript,有一种简单而优雅的方法来做到这一点:

for(var o of document.querySelectorAll('#DropList > option')) {
  o.remove()
}

其他回答

如果你正在使用JQuery,并且你的选择控件的ID为“DropList”,你可以这样删除它的选项:

$('#DropList option').remove();

实际上,它适用于任何选项列表,如数据列表。

希望能有所帮助。

去扭转。原因是每次移除后尺寸都会减小。

for (i = (len-1); i > -1; i--) {
    document.getElementById("elementId").remove(i);
}

项目应该反向删除,否则将导致错误。此外,我不建议简单地将值设置为null,因为这可能会导致意外的行为。

var select = document.getElementById("myselect");
for (var i = select.options.length - 1 ; i >= 0 ; i--)
    select.remove(i);

或者,如果你喜欢,你可以让它成为一个函数:

function clearOptions(id)
{
    var select = document.getElementById(id);
    for (var i = select.options.length - 1 ; i >= 0 ; i--)
        select.remove(i);
}
clearOptions("myselect");

这可以用来清除选项:

功能clearDropDown () { var选择=文档。getElementById(“DropList”), 选择。 当(长度正好…){ 选择。移除(长度正好); 的 的 <选择id=“DropList”> <选项> option_1 < /选项> <选项> option_2 < /选项> <选项> option_3 < /选项> <选项> option_4 < /选项> <选项> option_5 < /选项> 选择< - > <按钮onclick =“clearDropDown ()> revival巴顿list < - >

Try

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

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

或者如果你使用jQuery框架。

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