jQuery或Javascript或php脚本来检查每个元素并替换文本


jQuery or Javascript or php script to inspect each element and replace text

我正在寻找一个脚本来搜索和替换文本服务器端或客户端。

虽然用PHP替换字符串中的所有文本或用jQuery/Javascript替换页面上的所有文本很简单,但我还没能弄清楚如何使脚本根据父元素的类忽略文本的某些部分。

考虑以下情况:

<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"替换单词"keyword",预期的结果应该是:

<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语法来做到这一点。谁能帮我指出正确的方向或有任何意见,我将不胜感激。

谢谢

虽然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
    }
}) 

感谢大家及时而专业的意见。

像这样

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');

使用javascript遍历整个DOM树,专门查找textNodes (nodeType 3),并使用正则表达式将关键字替换为newWord(忽略大小写),然后递归地遍历每个节点的子节点。忽略<script><style>ignore类元素