繁体   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