首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

jQuery 智能提示關鍵字高亮:數字/逗號導致替換錯誤的修正方案

     編輯:程式設計綜合問答

問題根因

原代碼將 HTML 標簽替換為佔位符 [[[[i]]]],再全局替換關鍵字,**導致佔位符內的數字 i 被誤替換**(如輸入 1,[[[[1]]]] 變為 [[[[1]]]]),最終還原標簽失敗。

正確思路:遍歷文本節點而非替換整段 HTML

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); // 簡化:需傳遞元素引用
        }
    });
}

簡化版(針對 li 列表)

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);
    });
}

關鍵修正點

  • **不處理整段 HTML 字符串**,避免破壞標簽結構、誤替換屬性值、佔位符干擾。
  • 針對**具體子元素**(如 li)單獨替換內部 HTML,範圍可控。
  • 關鍵字正則轉義 replace(/[.*+?^${}()|[\]\\]/g, '\\$&') 防特殊字符破壞正則。
  • 用 包裹匹配文本,不改變 DOM 結構層級。

此模式適用于下拉提示、搜索結果高亮等場景,穩健且易維護。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved