且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用jquery从下拉列表中删除特定的项目

更新时间:2023-12-02 18:07:46

  $(#myList option:selected)。remove(); 

会工作






编辑:我误解了评论,但我会离开它作为一个通用的去除某些元素的例子。

如果你想根据数组中的值去除元素,你必须遍历数组:

  var $ list = $(#myList),
toRemove = $();

for(var i = selectedItems.length; i--;){
toRemove = toRemove.add($ list.find('option [value =''+ selectedItems [i] +']'));
}
toRemove.remove();

DEMO


I have a multi select dropdown list. I can get the array of selected values using:

selectedItems = $("#myList").val(); // works.

Now, how can I remove the selected items from the dropdown list?

$("#myList option:selected").remove();

will work.


Edit: I misunderstood the comment, but I will leave it as an example for removing certain elements in general.
If you want to remove the elements based on the value in the array, you have to loop over the array:

var $list = $("#myList"),
    toRemove = $();

for(var i = selectedItems.length; i--;) {
   toRemove = toRemove.add($list.find('option[value="' + selectedItems[i] + '"]'));
}
toRemove.remove();

DEMO