我的代码可以在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代码。
当前回答
今天我也遇到了同样的问题,我在重新加载选择框时做了如下操作。(在纯JS中)
var select = document.getElementById("item");
select.options.length = 0;
var opt = document.createElement('option');
opt.value = 0;
opt.innerHTML = "Select Item ...";
opt.selected = "selected";
select.appendChild(opt);
for (var key in lands) {
var opt = document.createElement('option');
opt.value = lands[key].id;
opt.innerHTML = lands[key].surveyNo;
select.appendChild(opt);
}
其他回答
我认为这是最好的sol. is $("#myselectid").html(");
如果您希望使用轻量级脚本,那么请使用jQuery。 在jQuery中,删除所有选项的解决方案如下:
$("#droplist").empty();
这是一种现代的纯JavaScript
document.querySelectorAll('#selectId option').forEach(option => option.remove())
这是一条很短的路:
document.getElementById('mySelect').innerText = null;
一行,没有for,没有JQuery,很简单。
这是最好的方法:
function (comboBox) {
while (comboBox.options.length > 0) {
comboBox.remove(0);
}
}