2010-10-20 103 views
3

我正在寫一個自定義控件,其中包含一個文本框輸入和一個無序列表項。當用戶輸入文本框時,我希望列表中的匹配文本加粗(包裹在<strong>標籤中)。Bolden匹配的搜索文本

//I use keyup so the value takes in to account the last keystroke. 
    $('#filterList').keyup(function() { 
     var $this = $(this); 

     //Clears the last function 
     clearTimeout($this.data('timer')); 

     //Runs the function after 400ms if no other keystrokes have taken place 
     $this.data('timer', setTimeout(function() { 
      var searchString = $this.val(); 

      $('li').each(function() { 

       //Remove old strong tags. 
       $(this).find('strong').replaceWith(function() { 
        return $(this).html(); 
       }); 

       //Here lies the issue... its close, but not quite there. 
       $(this).html($(this).html().replace(new RegExp(searchString, "ig"), '<strong>'+searchString+'</strong>')); 

      }); 

     }, 400)); 
    }); 

我遇到的問題是我想要的搜索是不區分大小寫。我能夠恰當地匹配文本,但替換它並保留原來的外殼正成爲一項挑戰。另外,我不知道如何從用戶的輸入中創建正則表達式。

建議請!先謝謝你!

+0

「LI」元素中的數據是怎樣的?它只包含純文本嗎? – Gumbo 2010-10-20 17:59:28

+0

它只是純文本。 – 2010-10-20 18:00:11

回答

3

考慮使用jQuery Highlight Plugin,您應該在幾分鐘內啓動並運行。

至於替換,您可以使用'<strong>$&</strong>' - $&將添加正則表達式匹配的全文。在這種情況下,這就是你要找的。工作示例:http://jsfiddle.net/kobi/cKVPY/

+0

謝謝Kobi,$&正是我一直在尋找的。高亮插件也很酷。 – 2010-10-20 18:01:47

+0

沒問題。祝你好運! – Kobi 2010-10-20 18:02:12