0

我正在尝试在 Internet Explorer 上修改这个简单的用户脚本以修改我自己的变量,这看起来很简单,但是当我用自己的变量替换变量以进行搜索和替换时,除非我刷新,否则网站会完全搞砸。

(function(){

    var arrGoogleInstances = document.body.innerHTML.match(/google/ig);

    if (arrGoogleInstances != null)
    {
        if (arrGoogleInstances.length > 0)
        {
            document.body.innerHTML = document.body.innerHTML.replace(/google/ig,'guuuuuuuugle');
            document.body.innerHTML = document.body.innerHTML.replace(/Google /ig,'Guuuuuuugle');   
        }   
    }

})();

例如,我尝试google用数字替换正则表达式术语。但是,该脚本似乎还没有工作,并且似乎弄乱了我的网站。

谁能告诉我这是为什么?

4

1 回答 1

1

不要使用innerHTML!(几乎,永远)
正在发生的事情是 HTML 结构本身的某些部分被丢弃,这取决于您发送到.replace(). 而且,使页面工作的所有 javascript 都被破坏或孤立。

正确的方法是使用 DOM 技术通过页面的文本节点进行递归。

代码是这样的,你可以在 jsfiddle 看到它的实际效果

replaceTextValues (document.body, /Google/ig, "Guuuuuuugle");


//-- Internet explorer doesn't define DOM2 constants!
if (typeof Node != "undefined") {
    TEXT_NODE       = Node.TEXT_NODE;
    ELEMENT_NODE    = Node.ELEMENT_NODE;
}
else {
    TEXT_NODE       = 3;
    ELEMENT_NODE    = 1;
}

function replaceTextValues (node, regex, replaceWith) {
    if (node.nodeType === TEXT_NODE) {
        node.nodeValue  = node.nodeValue.replace (regex, replaceWith);
    }
    else if (node.nodeType === ELEMENT_NODE) {
        for (var K = 0, numNodes = node.childNodes.length;  K < numNodes;  ++K) {
            replaceTextValues (node.childNodes[K], regex, replaceWith);
        }
    }
}
于 2012-12-26T23:46:09.807 回答