jQuery或Javascript或php脚本来检查每个元素并替换文本
我正在寻找一个脚本来搜索和替换服务器端或客户端的文本 虽然用PHP替换字符串中的所有文本或用jQuery/Javascript替换页面上的所有文本都很简单,但我还没有弄清楚如何根据父元素的类使脚本忽略文本的某些部分 考虑以下情况:jQuery或Javascript或php脚本来检查每个元素并替换文本,javascript,php,jquery,text,filter,Javascript,Php,Jquery,Text,Filter,我正在寻找一个脚本来搜索和替换服务器端或客户端的文本 虽然用PHP替换字符串中的所有文本或用jQuery/Javascript替换页面上的所有文本都很简单,但我还没有弄清楚如何根据父元素的类使脚本忽略文本的某些部分 考虑以下情况: <div> <span> This keyword should be replaced. </span> <span class="ignore"> thi
<div>
<span>
This keyword should be replaced.
</span>
<span class="ignore">
this keyword should be ignored.
</span>
<span>
This keyword should be replaced.
<span class="ignore">
this keyword should be ignored.
</span>
</span>
<span class="ignore">
this keyword should be ignored because of class name.
<span>
this keyword should also be ignored because it's a child of an ignored element.
</span>
</span>
</div>
这个关键字应该被替换。
应忽略此关键字。
这个关键字应该被替换。
应忽略此关键字。
由于类名的原因,应忽略此关键字。
这个关键字也应该被忽略,因为它是被忽略元素的子元素。
如果我想将“关键字”一词替换为“cow”,预期结果应该是:
<div>
<span>
This cow should be replaced.
</span>
<span class="ignore">
this keyword should be ignored.
</span>
<span>
This cow should be replaced.
<span class="ignore">
this keyword should be ignored.
</span>
</span>
<span class="ignore">
this keyword should be ignored because of class name.
<span>
this keyword should also be ignored because it's a child of an ignored element.
</span>
</span>
</div>
这头牛应该换掉。
应忽略此关键字。
这头牛应该换掉。
应忽略此关键字。
由于类名的原因,应忽略此关键字。
这个关键字也应该被忽略,因为它是被忽略元素的子元素。
到目前为止,我想到的最简单的逻辑是
1.递归地检查每个子节点
及
2.或者替换节点文本
或
3.如果发现类“ignore”,则忽略节点及其子节点
我仍在试图找到jQuery语法来实现这一点。任何能帮我指出正确方向或有任何意见的人,我都会非常感激
谢谢诸如此类的事
function replaceKeywords(keyword, newWord) {
for (var i = 0; i < document.childNodes.length; i++) {
checkNode(document.childNodes[i]);
}
function checkNode(node) {
var nodeName = node.nodeName.toLowerCase();
if (nodeName === 'script' || nodeName === 'style' || ~(node.className || "").indexOf('ignore')) { return; }
if (node.nodeType === 3) {
var text = node.nodeValue;
var regEx = new RegExp(keyword, 'gi');
var newText = text.replace(regEx, newWord);
node.nodeValue = newText;
}
if (node.childNodes.length > 0) {
for (var j = 0; j < node.childNodes.length; j++) {
checkNode(node.childNodes[j]);
}
}
}
}
//Use like
replaceKeywords('keyword','cow');
函数替换关键字(关键字,新词){
对于(var i=0;i0){
对于(var j=0;j
使用javascript遍历整个DOM树,专门查找textNodes(nodeType 3),并使用正则表达式将关键字替换为新词(忽略大小写),然后递归遍历每个节点的子节点。忽略
,
和类为忽略的元素虽然Ojay的解决方案也可以工作,但我最终还是使用了Arun p Johny解决方案的一点派生,因为jQuery库已经链接到了标题中。它比我原来的逻辑更有效,因为不需要显式递归
我会在这里再次分享,以防其他人有类似的需求
$('*').not('.ignore, .ignore *').contents().each(function () { //select all nodes except for those with the class ignore
if (this.nodeType == 3) { //if this is a text node
this.nodeValue = this.nodeValue.replace(/keyword/g, 'cow'); //replace text
}
})
感谢大家的及时和专业的意见。请尝试感谢您提供的快速而优雅的解决方案,Johny。它工作得很好。我将您的“#ct span”更改为“#ct*”,以使其更通用。代码工作得非常完美。谢谢你的快速回复,Ojay。