2017-04-07 46 views
0

我試圖實施搜索表,我在網上找到了答案,我試了一下,它工作正常!突出搜索文字與jquery

現在我想強調(改變文本顏色:文本顏色類=藍色文本)該搜索關鍵字表格單元格中,我尋找這個答案,但我沒有發現任何有用的!

我的HTML是

<table class="stdtable"> 
    <tr> 
    <td id="stdname">Name</td> 
    <td id="stdreg">Reg. No.</td> 
    <td id="stdparent">Parent</td> 
    <td id="stdgrp">Group</td> 
    <td id="action">Action</td> 
    </tr> 
</table> 

和jQuery是

$("#filter").on("keyup", function() { 
    var searchKey = $(this).val().toLowerCase(); 
    $(".stdtable tr #stdname").each(function() { 
     var searchStr = $(this).text().toLowerCase(); 
     if (searchStr.indexOf(searchKey)!=-1) { 
      $(this).parent().show(); 
     } 
     else { 
      $(this).parent().hide(); 
     } 
    }); 
}); 

我怎麼能凸顯搜索文本? 如果我搜索ñ文本名稱無應該改變顏色

,如果我清除搜索字段我需要清除的文字顏色也

+0

剝離跨度聲明試試[大關。 JS](https://markjs.io/)? – dude

回答

2

我不知道設置你有,但我會做一個類「突出顯示」 並給這個類的屬性:color: blue;或任何其他CSS特性你想要的特殊結果。 然後

$("#stdname").addClass("highlighted"); 

$("#stdname").removeClass("highlighted"); 

當您刪除搜索字段

編輯:離開上面有人希望所有的文字。

你可以採取

var s = $(this).val(); 
var txt = $("#stdname").val().replace(s, '<span style="color: blue">' + s + '</span>'); 
$("#stdname").val(txt); 

請注意,你要結束了奇怪的行爲,如果你不從$("#stdname").val()每次關鍵是高達

+0

不適用於整個字符串!只有那些我正在搜索的文字 –

+0

我修正了它。嘗試類似的東西,它應該能夠改變顏色。爲了清除,您必須刪除span語句並將其替換爲''>>「'跨度之間的字符串。 –