我的代码可以在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 (comboBox) {
while (comboBox.options.length > 0) {
comboBox.remove(0);
}
}
其他回答
可以使用以下命令清除所有元素。
var select = document.getElementById("DropList");
var length = select.options.length;
for (i = length-1; i >= 0; i--) {
select.options[i] = null;
}
要删除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()方法重新排列选项集合时。这样,就保证了要删除的元素仍然存在!
最简单的解决方案是最好的,所以你只需要:
var list = document.getElementById('list'); while (list.firstChild) { list.removeChild (list.firstChild); } <选择id = "列表" > <选项值= " 0 " > 0 < /选项> <选项值= " 1 " > 1 > < /选项 < /选择>
使用PrototypeJS:
$('yourSelect').select('option').invoke('remove');
这是最好的方法:
function (comboBox) {
while (comboBox.options.length > 0) {
comboBox.remove(0);
}
}