使用jQuery,从下拉选择框中移除所有条目的最简单方法是什么?

14

我有一个下拉列表,想要使用jQuery清除其中所有的选项。我在谷歌上搜索了很多关于删除选中项的链接,但是我希望清除下拉列表中的所有选项

什么是从下拉列表中删除所有选项的最佳方法?

3个回答

41

最佳方法:使用.empty()

$('select').empty();

演示

注意:当您想要删除元素本身以及其中的所有内容时,请使用.remove()


4
没想过这点,确实有更好的做法。 - Richard Dalton
真的。empty()是正确的选择。+1 - Boldewyn

7

3
$('option', the_select_element).remove();

如果您想保留所选内容:

$('option:not(:selected)', the_select_element).remove();

在纯JS中也非常简单(感谢@Austin France!):

// get the element
var sel = document.getElementById("the_select_ID");
// as long as it has options
while (sel.options.length) {
  // remove the first and repeat
  sel.remove(0);
}

简单的JS方法:var options = el.options; while (options.length) options[0].remove(); - Austin France
它的工作方式有点不同:while (select_element.options.length) select_element.remove(0); 但是没错。感谢提到本地接口! - Boldewyn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接