簡體   English   中英

如何使用jQuery從選擇元素中刪除選項?

[英]How to remove options from select element using jquery?

我有n個這樣的下拉菜單:

<select id="select1">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

<select id="select2">
 <option>1</option>
 <option>2</option>
 <option>3</option>
</select>

具有相同的選項。 所有選項都應該是唯一的,因此一旦在一個組合框中選擇了該選項,就應將其從其他組合中刪除。 因此,如果用戶在select1中選擇“ 1”,則select2中將只有選項“ 2”和“ 3”。

現在, jQuery根據選定的Radio禁用SELECT選項(需要對所有瀏覽器的支持)提供了一個不錯的解決方案,但是如何修改它以使用select而不是單選按鈕呢?

你是這個意思嗎?

這將從#select1 #select2中刪除所有內容:

$("#select2 option").each(function() {
    if($("#select1 option[value=" + this.value + "]").length)
        $(this).remove();
});

這是刪除所有重復項的另一種選擇:

$("select").each(function() {
  var select = $(this);  
  select.children("option").each(function() {
    $('select').not(select).children("option[value=" + this.value + "]").remove();
  });
});

這將刪除所有重復項,僅在找到它的第一個<select>保留選項。

更新您的評論:

$("#select1").change(function() {
 $("#select2 option[value=" + $(this).val()+ "]").remove();
});

或者,如果選擇具有相同順序的相同選項。

$('select').change(function() {
    var selectedIndex = $(this).find(':selected').index();    
    $('select').not(this).find('option:nth-child(' + selectedIndex + ')').remove();
)};

我認為這種方式速度更快(但不易閱讀)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM