html 和ajax 部分就不寫了,只需將需要匹配的文字傳進去就可以了
比如匹配后台傳回的字符串data.content中的關鍵詞:直接調用:
data.content = highLightKeywords(data.content,keywords)即可
以下兩個函數分辨是匹配1:匹配關鍵詞words中每一個字符,2:匹配整個關鍵詞words
//高亮關鍵字 text =>內容 words:關鍵詞 tag 被包裹的標簽 //匹配每一個關鍵字字符 function highLightKeywords(text, words, tag) { tag = tag || 'span';// 默認的標簽,如果沒有指定,使用span var i, len = words.length, re; for (i = 0; i < len; i++) { // 正則匹配所有的文本 re = new RegExp(words[i], 'g'); if (re.test(text)) { text = text.replace(re, '<'+ tag +' class="highlight">$&</'+ tag +'>'); } } } return text; }