gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:38:22 24 4
gpt4 key购买 nike

我需要使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com