1.首先確定高亮樣式
.highlight {color: red; }
2.高亮方法text是文本內容,words關鍵字,tag爲自定義標籤
function highlight(text, words, tag) {
// 默認的標籤,如果沒有指定,使用span
tag = tag || '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;
}
3.獲取頁面節點調用方法,該節點存在多個相同的用each循環調用
var elements = $(".sewageCheckjianhua");
var keywords = name.replace(/(\s,|,\s)/g, ',').split(',');
elements.each(function () {
$(this).html(highlight($(this).html(),keywords));
})
4.效果
5.取消高亮;text文本,tag自定義標籤
function unhighlight(text, tag) {
// 默認的標籤,如果沒有指定,使用span
tag = tag || 'span';
var re = new RegExp('(<'+ tag +'.+?>|<\/'+ tag +'>)', 'g');
return text.replace(re, '');
}