原代碼將 HTML 標簽替換為佔位符 [[[[i]]]],再全局替換關鍵字,**導致佔位符內的數字 i 被誤替換**(如輸入 1,[[[[1]]]] 變為 [[[[1]]]]),最終還原標簽失敗。
function highlightKeyword(containerId, keyword, color) {
if (!keyword) return;
const $container = $('#' + containerId);
const words = keyword.split(',').filter(w => w.trim());
$container.contents().each(function() {
if (this.nodeType === 3) { // 文本節點
let text = this.nodeValue;
words.forEach(w => {
const regex = new RegExp(`(${w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
text = text.replace(regex, `$1`);
});
// 替換文本節點為文本+span混合內容
$(this).replaceWith(text);
} else if (this.nodeType === 1) { // 元素節點,遞歸處理子節點
highlightKeyword(this.id || '', keyword, color); // 簡化:需傳遞元素引用
}
});
}
function setHeightKeyWord(id, keyword, color) {
if (!keyword) return;
const words = keyword.split(',').filter(w => w.trim());
$(`#${id} > li`).each(function() {
let html = $(this).html();
words.forEach(w => {
const regex = new RegExp(`(${w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
html = html.replace(regex, `$1`);
});
$(this).html(html);
});
}
li)單獨替換內部 HTML,範圍可控。replace(/[.*+?^${}()|[\]\\]/g, '\\$&') 防特殊字符破壞正則。 包裹匹配文本,不改變 DOM 結構層級。此模式適用于下拉提示、搜索結果高亮等場景,穩健且易維護。