2011-04-18 45 views
0

我旁邊HTML:jQuery的搜索多維UL列表

<input type="text" id="search" name="searchword" value="" /> 
<ul id="search_list"> 
    <li>first</li> 
    <li>second</li> 
    <li>third 
     <ul> 
      <li>aaa</li> 
      <li>bbbb 
       <ul> 
        <li>111111</li> 
        <li>22222</li> 
        <li>3333</li> 
       </ul> 
      </li> 
      <li>cccc</li> 
     </ul> 
    </li> 
</ul> 

而且我想通過輸入來搜索這個列表。 我鍵入文本輸入和<li><ul>的哪些不是搜索結果必須隱藏。

非常感謝你和對不起我的英語不好

+0

您是否試圖編寫代碼來執行此操作?什麼是示例搜索輸入? – 2011-04-18 20:31:57

+0

讓我們假設我輸入「11」。 我這種情況下

  • 第一個
  • 第二個
  • 應該隱藏,因爲它們不是搜索結果。 – Wizard4U 2011-04-18 20:33:37

    回答

    5

    使用KEYUP,模糊或當你想搜索和過濾發生改變依賴。

    $('#search').change(function() { 
        var searchTerms = $(this).val(); 
    
        $('li').each(function() { 
         var hasMatch = searchTerms.length == 0 || $(this).is(':contains(' + searchTerms + ')'); 
    
         $(this).toggle(hasMatch); 
        }); 
    }); 
    

    編輯:使解決方案稍微冗長,使其可以更容易閱讀。

    這是fiddle

    +0

    優秀,永遠不會說這很簡單。 非常感謝。 – Wizard4U 2011-04-18 20:37:00

    +2

    +1:我建議在搜索框中添加一個沒有回退的內容,例如'if(searchTerms.length == 0){$('li')。show();返回; }' – 2011-04-18 20:41:37

    +0

    好主意,因爲我非常確定在搜索框中沒有任何內容會使其失敗。 – 2011-04-18 20:44:25