我的代码可以在IE中运行,但在Safari、Firefox和Opera中会崩溃。(惊喜)
document.getElementById("DropList").options.length=0;
经过搜索,我了解到它不喜欢的是长度=0。 我试过了……选项=null和var clear=0...长度=clear,结果相同。
我一次对多个对象这样做,所以我正在寻找一些轻量级的JS代码。
我的代码可以在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);
}
while(document.getElementById("DropList").childNodes.length>0)
{
document.getElementById("DropList").removeChild(document.getElementById("DropList").childNodes[0]);
}
如果你正在使用JQuery,并且你的选择控件的ID为“DropList”,你可以这样删除它的选项:
$('#DropList option').remove();
实际上,它适用于任何选项列表,如数据列表。
希望能有所帮助。
注意,一个选择可以同时具有这两种情况 - optgroup & -选项集合 就像它的孩子一样。
So,
方法# 1
var selectElement = document.getElementById('myselectid');
selectElement.innerHTML = '';
方法# 2
var selectElement = document.getElementById('myselectid');
selectElement.textContent = '';
我测试过,两者都可以在Chrome上运行。 我喜欢简单的,老式的方法#1。
对于Vanilla JavaScript,有一种简单而优雅的方法来做到这一点:
for(var o of document.querySelectorAll('#DropList > option')) {
o.remove()
}