jquery - 在正文中搜索字符串,然后搜索样式

标签 jquery replace contains nodevalue

我需要使用 jQuery 搜索文档来查找特定单词。它实际上是一个品牌名称,无论在哪里使用都必须是粗体和斜体。

我可以使用 :contain 来做到这一点,但只能基于单个元素。我需要能够浏览 anchor 、列表 div 等。

$( "a:contains('brand name')" ).html().replace('brand name'.... 

任何想法将不胜感激。

更新: 我已经做到了这一点,它可以工作并替换页面上的所有内容,但我现在需要用一个类包装在一个跨度中。如此接近,但被这个问题难住了。再次感谢您的想法。

    $("body *").contents().each(function() {
  if(this.nodeType==3){
    this.nodeValue = this.nodeValue.replace(/brandname/g, 'colour');

  }
});

最佳答案

您可以用文档片段替换文本节点。这允许您对文本和样式节点进行分组,并将其与现有的文本节点交换。

var x = 0;
$("body *").contents().each(function() {

   if (this.nodeType == 3 && this.parentElement.tagName != "SCRIPT") {

     var text = this.nodeValue;
     var i = 0, lastIndex = 0;
     var search = /brandname/ig;
     var result;
     var parent = this.parentNode;
     var textNode = null;
     var highlight = null;
     var textRange = "";
     var fragment = document.createDocumentFragment();

     // Do search
     while ((result = search.exec(text)) !== null) {
    
       // add plain text before match
       textRange = text.substring(lastIndex, result.index);
       if (textRange != '') {
         textNode = document.createTextNode(textRange);
         fragment.appendChild(textNode);
       }
       
       // add highlight elements
       highlight = document.createElement('span');
       highlight.innerHTML = result[0];
       highlight.className = "hi";
       fragment.appendChild(highlight);
       lastIndex = search.lastIndex;
     }

     // Add trailing text
     textRange = text.substring(lastIndex);
     if (textRange != '') {
       textNode = document.createTextNode(textRange);
       fragment.appendChild(textNode);
     }
     
     // Replace textNode with our text+highlight
     if(fragment.children.length > 0) {
       this.parentNode.replaceChild(fragment, this);
     }
   }

 });
span.hi {
  background-color: #FFCC00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  Hello world this is my brandname. The BrAnDNAMe is regex matched and we can change subelements like "<a href=''>Brandname</a>." It should not replace <b>elements</b> that don't match.
</p>

关于jquery - 在正文中搜索字符串,然后搜索样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33804283/

相关文章:

java - GAE - 使用枚举字段和 'contains' 运算符过滤数据时 JDO 查询失败

jquery获取变量中的最后一个对象

javascript - 仅绘制 JSON 输出的一部分的图形

jquery - 切换页面当前部分的菜单颜色

javascript - 将 $watch 附加到指令中的输入字段

string - 将一个字符替换为另一个字符,反之亦然

c - 我如何调整此算法以处理多次出现的要修改的关键字?

powershell - 根据下一行查找并替换为 PowerShell

python - .query() 用于否定 str.contains()?

typescript - cypress.should 包含带有变量和子字符串的正则表达式