Javascript - 使用 innerHTML 替换 html

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15618470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:25:47  来源:igfitidea点击:

Javascript - Replace html using innerHTML

javascriptinnerhtml

提问by Dexter

I'm trying to replace html using innerHTML javascript.

我正在尝试使用 innerHTML javascript 替换 html。

From:

从:

aaaaaa/cat/bbbbbb

To:

到:

<a href="http://www.google.com/cat/world">Helloworld</a>

This's my code

这是我的代码

<html>
<head>
</head>
<body>
<p id="element1">aaaaaa/cat/bbbbbb</p>

<script language="javascript">
var strMessage1 = document.getElementById("element1") ;
strMessage1.innerHTML = strMessage1.innerHTML.replace( /aaaaaa./g,'<a href=\"http://www.google.com/') ;
strMessage1.innerHTML = strMessage1.innerHTML.replace( /.bbbbbb/g,'/world\">Helloworld</a>') ;
</script>
</body>
</html>

When i run this code it disappears Helloworld hyperlink. what I'm doing wrong. Please help.

当我运行此代码时,它会消失 Helloworld 超链接。我做错了什么。请帮忙。

Thank you for all your help.

谢谢你的帮助。

回答by Antony

You should chain the replace() together instead of assigning the result and replacing again.

您应该将 replace() 链接在一起,而不是分配结果并再次替换。

var strMessage1 = document.getElementById("element1") ;
strMessage1.innerHTML = strMessage1.innerHTML
                        .replace(/aaaaaa./g,'<a href=\"http://www.google.com/')
                        .replace(/.bbbbbb/g,'/world\">Helloworld</a>');

See DEMO.

演示

回答by Guffa

You are replacing the starting tag and then putting that back in innerHTML, so the code will be invalid. Make all the replacements before you put the code back in the element:

您正在替换起始标记,然后将其放回 中innerHTML,因此代码将无效。在将代码放回元素之前进行所有替换:

var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;