innerHTML 替換,避免事件綁定丟失、表單重置。(function ($) {
$.fn.highlight = function (keywords, options) {
const opts = $.extend({
className: 'highlight',
caseSensitive: false,
wordsOnly: false, // 全詞匹配
clearPrevious: true
}, options);
const $container = this;
if (opts.clearPrevious) {
$container.find('.' + opts.className).each(function () {
this.parentNode.replaceChild(document.createTextNode(this.textContent), this);
});
}
if (!keywords) return $container;
const kwArray = Array.isArray(keywords) ? keywords : [keywords];
const regexFlags = opts.caseSensitive ? 'g' : 'gi';
// 遞歸處理文字節點
function processNode(node) {
if (node.nodeType === Node.TEXT_NODE) {
let text = node.nodeValue;
let matched = false;
kwArray.forEach(kw => {
const escaped = kw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const pattern = opts.wordsOnly ? '\\b' + escaped + '\\b' : escaped;
const regex = new RegExp(pattern, regexFlags);
if (regex.test(text)) {
matched = true;
text = text.replace(regex, match => `${match}`);
}
});
if (matched) {
const wrapper = document.createElement('span');
wrapper.innerHTML = text;
node.parentNode.replaceChild(wrapper, node);
// 扁平化:將 wrapper 子節點提升
while (wrapper.firstChild) wrapper.parentNode.insertBefore(wrapper.firstChild, wrapper);
wrapper.parentNode.removeChild(wrapper);
}
} else if (node.nodeType === Node.ELEMENT_NODE) {
// 跳過 script/style/textarea 等
if (!/^(script|style|textarea|input|select|option)$/i.test(node.tagName)) {
[...node.childNodes].forEach(processNode); // 複製陣列避免動態修改影響迭代
}
}
}
this.each(function () { processNode(this); });
return $container;
};
})(jQuery);
<div id="content">
<p>JavaScript 是一種直譯式程式語言。</p>
<p>它廣泛用於 Web 開發。</p>
</div>
<script>
$('#content').highlight(['JavaScript', 'Web', '開發'], {
className: 'kw-highlight',
caseSensitive: false
});
</script>
<style>
.kw-highlight { background: #fff3cd; padding: 0 2px; border-radius: 2px; }
</style>
$.fn.simpleHighlight = function (query, className = 'highlight') {
if (!query) return this;
const regex = new RegExp('(<[^>]*>)|(' + query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
return this.each(function () {
this.innerHTML = this.innerHTML.replace(regex, (m, tag, text) => tag ? tag : `${text}`);
});
};
缺點:會破壞現有事件綁定、表單狀態、輸入框內容;不支援巢狀高亮。
{ highlightedCount: 12, keywordCounts: { 'JavaScript': 3, 'Web': 2 } }。document.querySelector('.highlight').scrollIntoView()。.unhighlight() 方法還原文字節點。TreeWalker 遍歷文字節點,配合 requestIdleCallback 分批處理。