我使用下面的jquery函數突出顯示div標籤內的單詞。jQuery的突出顯示不能正常工作與連續搜索
jQuery.fn.highlight = function (str, className) {
var regex = new RegExp(str, "gi");
return this.each(function() {
$(this).contents().filter(function() {
return this.nodeType == 3 && regex.test(this.nodeValue);
}).replaceWith(function() {
return (this.nodeValue.replace("<", "<").replace(">", ">") || "").replace(regex, function (match) {
return "<span class=\"" + className + "\">" + match + "</span>";
});
});
});
};
其實它的工作只有一個字的組合,但它錯過了重複。我使用了mark.js,但是我對mark.js有其他限制。任何人都可以告訴我這個代碼有什麼問題嗎?
在這裏看到有關如何替換字符串中所有出現的一些信息:http://stackoverflow.com/questions/1144783/how-to-replace-all javascript中的字符串問題 – SquareCat
mark.js有什麼問題?使用'.replace()'是邪惡的,因爲它會銷燬事件並觸發DOM的再生。你一定要繼續mark.js。 – dude