有时候需要我们把一些特殊的关键字给高亮显示出来,使他人可以更直观的查看,输入的内容是否有非法的关键字!!
这里,我们使用tp框架来做实例。
1、添加我们需要作用的元素
<table width="100%" class="table_form" id="waiDiv"> <tr> <th>用户昵称</th> <th>内容</th> <th>添加时间</th> </tr> <foreach name="data" item="v" key="k" > <tr> <td>{$v.alias}</td> <td>{$v.content}</td> <td>{$v.tm}</td> </tr> </foreach> </table>
2、添加 js效果
<table width="100%" class="table_form" id="waiDiv"> <tr> <th>用户昵称</th> <th>内容</th> <th>添加时间</th> </tr> <foreach name="data" item="v" key="k" > <tr> <td>{$v.alias}</td> <td>{$v.content}</td> <td>{$v.tm}</td> </tr> </foreach> </table> <script> /* * 参数说明: * obj: 对象, 要进行高亮显示的html标签节点. * hlWords: 字符串, 要进行高亮的关键词词, 使用 竖杠(|)或空格分隔多个词 . * bgColor: 背景颜色,默认为红色. */ function MarkHighLight(obj, hlWords, bgColor) { hlWords = AnalyzeHighLightWords(hlWords); if (obj == null || hlWords.length == 0) return; if (bgColor == null || bgColor == "") { bgColor = "red"; } MarkHighLightCore(obj, hlWords); //执行高亮标记的核心方法 function MarkHighLightCore(obj, keyWords) { var re = new RegExp(keyWords, "i"); var style = ' style="background-color:' + bgColor + ';" ' for (var i = 0; i < obj.childNodes.length; i++) { var childObj = obj.childNodes[i]; if (childObj.nodeType == 3) { if (childObj.data.search(re) == -1) continue; var reResult = new RegExp("("+keyWords+")", "gi"); var objResult = document.createElement("span"); objResult.innerHTML = childObj.data.replace(reResult, "<span" + style + ">$1</span>"); //if (childObj.data == objResult.childNodes[0].innerHTML) continue; obj.replaceChild(objResult, childObj); } else if (childObj.nodeType == 1) { MarkHighLightCore(childObj, keyWords); } } } //分析关键词 function AnalyzeHighLightWords(hlWords) { if (hlWords == null) return ""; hlWords = hlWords.replace(/\s+/g, ",").replace(/\|+/g, ","); hlWords = hlWords.replace(/(^\|*)|(\|*$)/g, ""); if (hlWords.length == 0) return ""; var wordsArr = hlWords.split(","); if (wordsArr.length > 1) { var resultArr = BubbleSort(wordsArr); var result = ""; for (var i = 0; i <= resultArr.length; i++) { result = result + "," + resultArr[i]; } return result.replace(/(^\|*)|(\|*$)/g, ""); } else { return hlWords; } } //利用冒泡排序法把长的关键词放前面 function BubbleSort(arr) { var temp, exchange; for (var i = 0; i < arr.length; i++) { exchange = false; for (var j = arr.length - 2; j >= i; j--) { if ((arr[j + 1].length) > (arr[j]).length) { temp = arr[j + 1]; arr[j + 1] = arr[j]; arr[j] = temp; exchange = true; } } if (!exchange) break; } return arr; } } //end window.onload = function() { var obj = document.getElementById("waiDiv"); var json = '{$keyword}'; var data = eval('('+json+')'); ch = new Array; ch = data.split(","); var length = ch.length; for(var i=0;i<length;i++) { //alert(ch[i]); //document.write(ch[i],"<br>"); MarkHighLight(obj, ch[i], "Red"); } }; </script>
3、后端处理
后端关键字返回json串即可。
本文为崔凯原创文章,转载无需和我联系,但请注明来自冷暖自知一抹茶ckhttp://www.cksite.cn