代码如下:
<html> <head> <title>高亮显示搜索关键字-www.jb200.com</title> <style type="text/css"> .highlight {color:red;} </style> <script type="text/javascript"> function highword(nWord){ var table = document.getElementById("row"); if (table!=null) highLightKeyWord(table,nWord,"highlight"); } function highLightKeyWord(eTable,strKeyWord,className){ var rows = eTable.rows; //var oRegExp = new RegExp("" + strKeyWord + "","g");//g表示全局搜索,i表示忽略大小写 var oRegExp = new RegExp("" + strKeyWord + "","img"); for(var i=0,rl=rows.length;i<rl;i++){ var r = rows.item(i); for(var j=0,tl=r.cells.length;j<tl;j++){ var innerText = r.cells.item(j).innerHTML; if (innerText.indexOf("<")<0 && i>0) { var searchValue=innerText.match(oRegExp,strKeyWord); //var tmp = innerText.replace(oRegExp,"<span class='"+className+"'>"+strKeyWord+"</span>"); var tmp = innerText.replace(oRegExp,"<span class='"+className+"'>"+searchValue+"</span>"); r.cells.item(j).innerHTML = tmp; } } } } </script> </head> <body onload="highword('Nms')"> <table id="row"> <tr> <th width=100 align="left">列1</th><th width=100 align="left">列2</th><th width=100 align="left">列3</th> </tr> <tr> <td>NMSABC</td> <td>NmsAbc</td> <td>nmsabc</td> </tr> <tr> </table> </body> </html>
#---
好东西不怕多,再为大家友情提供另一个例子,有空就来脚本学堂转转吧,总会有惊喜。
广告穿插完毕,呵呵!
#---
附,搜索多个关键字之后,高亮显示,并且忽略大小写:
<script> /** * 高亮显示搜索关键字 * www.jb200.com */ function HighLight(nWord){ if(nWord!=''){ var keyword = document.body.createTextRange(); while(keyword.findText(nWord)){ keyword.pasteHTML("<span style='color:blue;background-color:#FFFF00'>" + keyword.text + "</span>"); keyword.moveStart('character',1); } } } function highword(nWord){ var array = nWord.split(" "); for(var i=0;i<array.length;i++){ alert(array[i]); HighLight(array[i]); } } </script> <body onload="highword('LI jin')"> <table id="row"> <tr><td>liujinzhong liujinzhong liuzhong</td></tr> <tr><td>liujinzhong liujinzhong liuzhong</td></tr> <tr><td>LiuJinzhong LIUjinzhong liuzhong</td></tr> </table> <p>liujinzhong liujinzhong liuzhong</p> </body>