簡體   English   中英

regexp查找html標簽

[英]regexp finds html tags

我使用jQuery編寫了一個簡單的“搜索功能”。 您在框中輸入一些文本,它將返回您搜索的頁面上的文本。 但是,如果我鍵入單詞“ the”,則搜索結果會返回<thead></thead>並突出顯示“ the”。 我該如何做,以至於找不到這樣的html標簽? 當我輸入“ edit”並返回名為“ edit ....”的圖像而該圖像消失且“ edit”突出顯示時,會發生類似的情況。

我以element開頭的行嘗試了一些不同的事情,因為我認為這就是問題所在。

        function highliter(word, id){
            $('*').removeClass('highlight');
            var rgxp = new RegExp(word, 'g');
            var repl = '<span class="highlight">' + word + '</span>';
            var element = document.getElementById(id);
            element.innerHTML = element.innerHTML.replace(/word/g, repl);
            // element.innerHTML = element.innerHTML.replace(rgxp, repl);

            $('html, body').scrollTop($(".highlight").offset().top - 126);

好。 坦白地說,我對這種解決方案並不滿意,但它確實可以滿足您的要求,但希望能給您一些想法。

它分兩個步驟工作:

  • 首先處理包含目標單詞的所有元素的文本節點 ,並用特殊標記替換它(應該不太可能在源代碼中的其他地方找到-這是我不太滿意的技巧)
  • 然后使用正則表達式和html()方法將我們的標記替換為最終的替換模式(這部分與您的原始標記非常相似)

 function highliter(word, id) { var el = $('#' + id); var repl = '<span class="highlight">' + word + '</span>'; $('*').removeClass('highlight'); recursiveMarker(word, el); el.html(el.html().replace(/\\[MY_MARKUP\\]/g, repl)); } function recursiveMarker(word, parent) { var rgxp = new RegExp(word, 'g'); var repl = '[MY_MARKUP]'; parent.find(':contains(' + word + ')').contents().each(function(key, el) { if(this.nodeType == 3) { el.data = el.data.replace(rgxp, repl); } else { recursiveMarker(word, $(el)); } }); } highliter('div', 'container'); 
 .highlight { background-color:#ffff00; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <div>This is a div <span id="div">with a span whose id is 'div'</span></div> <div>This is another div</div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM