我的代码可以在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代码。
当前回答
注意,一个选择可以同时具有这两种情况 - optgroup & -选项集合 就像它的孩子一样。
So,
方法# 1
var selectElement = document.getElementById('myselectid');
selectElement.innerHTML = '';
方法# 2
var selectElement = document.getElementById('myselectid');
selectElement.textContent = '';
我测试过,两者都可以在Chrome上运行。 我喜欢简单的,老式的方法#1。
其他回答
使用JQuery是一种更漂亮、更短、更聪明的方法!
$('#selection_box_id').empty();
for (var opt of document.querySelectorAll('#DropList option'))
{
opt.remove();
}
这个解决方案也适用于optgroups。
这可以用来清除选项:
功能clearDropDown () { var选择=文档。getElementById(“DropList”), 选择。 当(长度正好…){ 选择。移除(长度正好); 的 的 <选择id=“DropList”> <选项> option_1 < /选项> <选项> option_2 < /选项> <选项> option_3 < /选项> <选项> option_4 < /选项> <选项> option_5 < /选项> 选择< - > <按钮onclick =“clearDropDown ()> revival巴顿list < - >
今天我也遇到了同样的问题,我在重新加载选择框时做了如下操作。(在纯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);
}
while(document.getElementById("DropList").childNodes.length>0)
{
document.getElementById("DropList").removeChild(document.getElementById("DropList").childNodes[0]);
}