日期:2014-05-16 浏览次数:20519 次
<!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Text</title> </head> <body> <label for="input">pattern:</label> <input id="pattern" name="input" type="input" value="\d+"/> <label for="flags">flags:</label> <input id="flags" name="flags" type="input" value="g"/> <input id="search" type="button" value="Search" /> <p>asdflasdjfk21312394293</p> <div>87dlksdjfa89098239lasdjkf</div> <script> var eDoc = document, ePattern = eDoc.getElementById("pattern"), eFlags = eDoc.getElementById("flags"), eSearch = eDoc.getElementById("search"); eSearch.onclick = function(){ var pattern = ePattern.value, flags = eFlags.value, reg = new RegExp(); reg.compile(pattern, flags); console.dir(reg); searchText(reg); } function searchText(reg){ var elems = Array.prototype.slice.call(document.body.getElementsByTagName("*"), 0); childNodes = null; for(var i = 0, len = elems.length; i < len; i++){ childNodes = elems[i].childNodes; if(childNodes.length === 1 && childNodes[0].nodeType === 3){ elems[i].innerHTML = childNodes[0].nodeValue.replace(reg, function(arg){ return "<span style='color: red'>" + arg + "</span>"; }); } } } </script> </body> </html>