2012-09-17 43 views
0

我得到了一定的字符串,並且我想突出顯示在文本輸入中鍵入的子字符串。突出顯示字符串中的單詞

這裏是一個小提琴:http://jsfiddle.net/rFGWZ/17/

它只是工作正常,當我鍵入初始字符串,但是當我型鐵。 15在輸入時,它不會突出顯示15,而是21而是......它總是突出顯示開始時的數字,所以有人可以幫我修改它,所以它會突出顯示我在文本輸入中輸入的字符串?

回答

2

你可以使用這樣的:

firstCell.html(id.replace(value, '<span class=highlight>'+value+'</span>')); 

代替

firstCell.html($("<span />").addClass("highlight").text(id.slice(0, value.length))); 
firstCell.append(id.slice(value.length, id.length)); 

演示:http://jsfiddle.net/qgBt8/

編輯:case insensitive version

+0

有沒有一種方法,使之不區分大小寫的,因爲萬一要是會有一些字母,它突出那些案例敏感性。謝謝。 – Sapp

+0

現在+1 :-)。 – Sapp

+1

以下是不區分大小寫的版本:http://jsfiddle.net/B5qLb/ –

0

我會用正則表達式來解決這個問題。這也考慮到了字符的情況。

jsFiddle

$("#search").on("keyup", function() { 
    var value = $(this).val(); 

    $("table tr").each(function(index) { 
     if (index !== 0) { 

      $row = $(this); 
      var firstCell = $row.children("td:first"); 

      var id = $row.children("td:first").text(); 
      if (id.indexOf(value) === -1) { 
       $row.children("td:first").text(id); 
       $row.hide(); 
      } 
      else { 
       var re = new RegExp(value, "g"); //global replace 
       firstCell.html(id.replace(re, "<span class=\"highlight\">" + value + "</span>"));//replace all instances of the characters 
       $row.show(); 
      } 
     } 
    }); 
});​ 
+0

當然,但是它仍然不支持不區分大小寫的字符,當字符串中有'M'和'm'時,我會輸入'm '在文字輸入中,那麼它只會突出顯示'm'而不是兩個。 – Sapp

+0

我不知道你需要它是不敏感的。看起來你已經得到了你的答案! – JoeFletch