我的代码可以在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代码。
当前回答
可以使用以下命令清除所有元素。
var select = document.getElementById("DropList");
var length = select.options.length;
for (i = length-1; i >= 0; i--) {
select.options[i] = null;
}
其他回答
while(document.getElementById("DropList").childNodes.length>0)
{
document.getElementById("DropList").removeChild(document.getElementById("DropList").childNodes[0]);
}
Try
document.getElementsByTagName("Option").length=0
或者可以查看removeChild()函数。
或者如果你使用jQuery框架。
$("DropList Option").each(function(){$(this).remove();});
项目应该反向删除,否则将导致错误。此外,我不建议简单地将值设置为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");
这是最好的方法:
function (comboBox) {
while (comboBox.options.length > 0) {
comboBox.remove(0);
}
}
以上答案的代码需要轻微更改以删除列表完整,请检查这段代码。
var select = document.getElementById("DropList");
var length = select.options.length;
for (i = 0; i < length;) {
select.options[i] = null;
length = select.options.length;
}
刷新长度,它将从下拉列表中删除所有数据。 希望这能帮助到一些人。