标签:
来张效果图:
输入关键字后:
本例子中主要用到的是jQuery的keyup()、each()和filter()方法。除此之外,还用到了javascript的RegExp对象和stringObject.replace()方法
源码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title></title> <style type="text/css"> body{ font: normal 12px Arial; } table th{ width: 100px; border-bottom: 1px solid; text-align:center; } table .matched{ font-weight:bolder; background-color:lightpink; } table tr{ text-align:left; } </style> <script src="../scripts/jquery-1.3.1.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#filterName").keyup(function () { var keyValue = $(this).val().trim(); var $input = $(this); clearTable(); if (!keyValue.length) { $("table tbody tr").show(); return false; }; $("table tbody tr").hide() .filter(function (index) { var _ = $(this); var f = false; f = (function () { try { $.each(_.children(), function () { var __ = $(this); var v = __.html(); var flag = false; flag = (function () { try { $.each(keyValue, function (index, value) { if (v.indexOf(value) > -1) {//存在 var reg = new RegExp(value,"gi"); v = v.replace(reg,function(word){ return "<span class=‘matched‘>"+word+"</span>"; }); __.html(v); throw (e); } }); } catch (e) { return true; } })(); if (flag) throw (e); }); } catch (e) { return true; } })(); return f; }).show(); }); function clearTable(){ $("table tbody tr").each(function(){ $(this).children().each(function(){ if($(this).children("span").length > 0){ var target = $(this).children("span"); target.replaceWith(target.html()); } }); }); } }); </script> </head> <body> <div> <br/> 筛选: <input id="filterName" /> <br/> </div> <table> <thead> <tr><th>姓名</th><th>性别</th><th>暂住地</th></tr> </thead> <tbody> <tr><td>张山</td><td>男</td><td>浙江宁波</td></tr> <tr><td>李四</td><td>女</td><td>浙江杭州</td></tr> <tr><td>王五</td><td>男</td><td>湖南长沙</td></tr> <tr><td>找六</td><td>男</td><td>浙江温州</td></tr> <tr><td>Rain</td><td>男</td><td>浙江杭州</td></tr> <tr><td>MAXMAN</td><td>女</td><td>浙江杭州</td></tr> <tr><td>王六</td><td>男</td><td>浙江杭州</td></tr> <tr><td>李字</td><td>女</td><td>浙江杭州</td></tr> <tr><td>李四</td><td>男</td><td>湖南长沙</td></tr> </tbody> </table> </body> </html>
标签:
原文地址:http://www.cnblogs.com/sxshijingjing/p/4218276.html