【问题标题】:Replace a phrase in a HTML document? [closed]替换 HTML 文档中的短语? [关闭]
【发布时间】:2014-02-04 04:54:08
【问题描述】:

是否可以用另一个短语替换 HTML 文档中的短语?我不确定 JavaScript 是否可以做到这一点,但这里有一个例子:

String thePhrase = "this is the phrase to replace";
String toReplace = "this is the phrase that replaces thePhrase";
replace(thePhrase, toReplace);

然后这样的东西会在 HTML 文档中搜索并用 toReplace 替换 thePhrase。

感谢任何可以提供帮助的人。

【问题讨论】:

  • 你查过什么吗?
  • 您需要将文档中的所有文本从 X 替换为 Y?
  • 在源头替换数据,而不是在加载客户端。或者在 PHP 中执行此操作。
  • 使用 querySelectorAll 获取您的 link 元素并在这些元素的 innerText/textContent 上进行替换

标签: javascript html


【解决方案1】:

执行此操作的正确方法是递归遍历页面上的每个节点,从 document.body 开始,每当您点击文本节点时,替换那里的文本。

var findAndReplaceAllText = function(node, needle, replacement){
    if(node.nodeName == 'SCRIPT') return; /* don't mess with script tags */
    if(node.nodeType == 3) /* if node type is text, replace text */
        node.nodeValue = node.nodeValue.replace(needle, replacement);
    for(var i = node.childNodes.length; i--;) /* loop through all child nodes */
        findAndReplaceAllText(node.childNodes[i], needle, replacement);
};
findAndReplaceAllText(document.body, /this/g, 'anything but that');

如果您直接使用innerHTML 或jQuery 的.html() 方法修改html,则很有可能会破坏页面上引用这些元素的其他脚本,例如事件处理程序。所以,这是一个更好的方法。

无论如何,如果您需要这样做,那么您很有可能以不正确的方式解决问题,应该尝试找到更好的方法来实现您的目标。

【讨论】:

    【解决方案2】:

    这里有一个使用 p 标签和 jQuery 的例子。希望对你有帮助

    var thePhrase = "this is the phrase to replace";
    var toReplace = "this is the phrase that replaces thePhrase";
    $("p").each(function(){
       var $this = $(this);
        if( $this.html() == thePhrase) {
            $this.html( toReplace );
        }
    });
    

    在这里查看它的演示 http://jsfiddle.net/sousatg/w3jCj/

    【讨论】:

    • 假设您在<p> 标记内有一个锚点<a> 标记,并附加了一个事件侦听器。该脚本会破坏该事件侦听器,因为原始的 <a> 标记将与绑定到它的所有事件一起丢失,因为您正在用新标记替换它们。
    • 正如你在这个例子中看到的jsfiddle.net/sousatg/w3jCj/5 它不会中断。
    • 哦,我看错了你的代码。我以为您实际上是在进行查找和替换。如果内部 html 与搜索字符串完全匹配,您的代码只会替换内容,所以没关系,我的错误 :)
    • 这可能被否决了,因为不应该涉及 jQuery,应该使用 .text() 而不是 .html()。在 vanilla JS 中,这将是 elem.textContent.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2018-09-30
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多