0

我需要使用 jquery 和 javascript 替换 DOM(内存中的网页)中的所有单词。我需要改变这个:

<html>
<head>
    Hi to all
</head>
<body>
    Hi to all
</body>
</html>

进入这个:

<html>
    <head>
        Bye to all
    </head>
    <body>
        Bye to all
    </body>
</html>

但不修改标签(只有那里的值)

一种尝试是:

jQuery.fn.replaceEachOne = function (objective, rep) {
    return this.each( function(){
                $(this).html( $(this).html().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
            }
        );
}

但是如果我放它,它会继续替换标签值并破坏页面。

帮助!!!

4

4 回答 4

1

如果您不希望它更改您的标签,为什么要修改“html”而不仅仅是文本?

jQuery.fn.replaceEachOne = 函数(目标,代表){
    返回 this.each(function(){
                $(this).text( $(this).text().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/ ;#~%"=-]*>]))', "ig"), rep) );
            }
        );
}
于 2011-01-18T21:43:10.523 回答
1

我猜标题中会有其他元素,而不是用新文本替换所有内容。试试这样的东西

$(function(){
  var element = $('body, head').find('*:contains("Hi to all")');
  element.html('Bye to all');
});
于 2011-01-18T20:58:31.470 回答
0

尽管效率低下,一种方法是:

var element = document.getElementsByTagName('html')[0];
element.innerHTML = element.innerHTML.replace('Hi to all', 'Bye to all');

如果需要,引号中的 'Hi to all' 也可以替换为正则表达式。

于 2011-01-18T21:40:09.127 回答
0

最后...

谢谢大家...

jQuery.fn.replaceEachOne = function (objective, reposition) {
    this.contents().each(function(){
        if (this.nodeType == Node.ELEMENT_NODE) {
            $(this).replaceEachOne(objective, reposition);
        } else if (this.nodeType == Node.TEXT_NODE) {
            var label = document.createElement("label");
            label.innerHTML = this.nodeValue.replace(objective, reposition);
            this.parentNode.insertBefore(label, this);
            this.parentNode.removeChild(this);
        }
    }); 
}
于 2011-01-19T15:33:23.770 回答