我的代码可以在IE中运行,但在Safari、Firefox和Opera中会崩溃。(惊喜)

document.getElementById("DropList").options.length=0;

经过搜索,我了解到它不喜欢的是长度=0。 我试过了……选项=null和var clear=0...长度=clear,结果相同。

我一次对多个对象这样做,所以我正在寻找一些轻量级的JS代码。


当前回答

我认为这是最好的sol. is $("#myselectid").html(");

其他回答

要删除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 select = document.getElementById("DropList");
var length = select.options.length;
for (i = 0; i < length;) {
  select.options[i] = null;
  length = select.options.length;
}

刷新长度,它将从下拉列表中删除所有数据。 希望这能帮助到一些人。

今天我也遇到了同样的问题,我在重新加载选择框时做了如下操作。(在纯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);

        }

这是一种现代的纯JavaScript

document.querySelectorAll('#selectId option').forEach(option => option.remove())

如果你正在使用JQuery,并且你的选择控件的ID为“DropList”,你可以这样删除它的选项:

$('#DropList option').remove();

实际上,它适用于任何选项列表,如数据列表。

希望能有所帮助。