2017-01-23 102 views
0

select元素我有JS是這樣的:過濾基於另一個不工作

$(document).ready(function() { 

    $("#DDL1").change(function() { 
     var thisValue = $(this).val(); 

     var $optGroups = $("#DDL2 optgroup"); 
     $optGroups.hide(); 

     switch (thisValue) { 
      case "11": 
       alert(thisValue); 
       $optGroups.filter("[label='label1']").show(); 
       break; 
     } 

    }); 
}); 

基本上,基於第一DDL的選擇。我想過濾:第二個..

當我運行這個,thisValue = 11,這是我想要的。但是$optGroups仍然會顯示所有的可選值。而我只希望顯示標籤爲label1的optgroup下的值。

任何解釋我可能做錯了什麼?

+0

如果你的'DDL1'是一個'select'元素,那麼原因可能是'optgroup'和'option'元素被瀏覽器以特殊方式處理,並且可能無法'顯示'/'通過CSS隱藏它們(jQuery所做的)。我認爲解決方案是臨時「移除」你不想展示的「optgroup」。 –

+0

@ZoltánTamási好的,除了我想展示的標籤之外,還有一種方法可以刪除所有其他標籤,而不必明確指定所有標籤? –

回答

1

如果您DDL1是select元素,那麼原因可能是optgroupoption元素以一種特殊的方式通過瀏覽器處理,它可能無法通過CSS show/hide他們(jQuery的做什麼)。

嘗試動態地插入匹配optgroup s這樣的東西。

$(document).ready(function() { 

    // grab out the initial optgroups from the select and keep them in memory 
    var $optGroups = $("#DDL2 optgroup").detach(); 

    $("#DDL1").change(function() { 
     var thisValue = $(this).val(); 

     // remove all the current optgroups from the select 
     $("#DDL2 optgroup").detach(); 

     switch (thisValue) { 
      case "11": 
       alert(thisValue); 
       // append the matching optgroups to the select 
       $optGroups.filter("[label='label1']").appendTo($("#DDL2")); 
       break; 
     } 

    }); 
}); 

請注意,代碼僅用於示例目的,未經任何測試。

+0

啊這工作。你能解釋爲什麼你使用'detach'兩次? –

+0

首先我得到最初的optgroups,所以我把它們全部放在內存中。在每次更改時,我必須清空選擇,因爲它可以具有先前插入的「optgroup」。我可以使用'empty'或'remove',但我不確定它們的任何可能的副作用(例如'remove'可能會殺死某些事件處理程序或附加到它們的DOM數據等等)。如果你想從他們的父母中移出元素,'detach'是IMO最安全的方式。 –

+0

謝謝!有沒有關於爲什麼一些瀏覽器不使用show和hide選擇元素的文檔? –

相關問題