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

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

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

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


当前回答

这可以用来清除选项:

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

其他回答

这是一条很短的路:

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

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

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

这是最好的方法:

function (comboBox) {
    while (comboBox.options.length > 0) {                
        comboBox.remove(0);
    }        
}

如果你必须支持IE,并且你的选择列表中有超过100个项目,我强烈建议你考虑用这样的函数替换选择:

function clearOptions(select) {
    var selectParentNode = select.parentNode;
    var newSelect = select.cloneNode(false); // Make a shallow copy
    selectParentNode.replaceChild(newSelect, select);
    return newSelect;
}

select参数应该是jquery选择器或文档中的元素。getElementBy电话。这样做的唯一缺点是,您丢失了连接到select的事件,但是当它从函数返回时,您可以轻松地重新附加它们。我正在处理一个有~3k项的选择,在IE9上清除选择需要4秒钟,这样我就可以用新内容更新它。这样做几乎是瞬间的事。

for (var opt of document.querySelectorAll('#DropList option'))
{ 
  opt.remove();
}

这个解决方案也适用于optgroups。