Why does my innerHTML disappear when replacing it?
发布时间
阅读量:
阅读量
题意 :
为什么我替换 innerHTML 时它会消失?
问题背景:
I'm trying to replace some HTML using .innerHTML and .replace.
我正在尝试使用 .innerHTML 和 .replace 替换一些 HTML。
From:
aaaaaa/cat/bbbbbb
To: 将上面的代码修改成:
<a href="http://www.google.com/cat/world">Helloworld</a>
This is my code: 这是我的代码:
<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>
The execution of this code causes the Helloworld hyperlink to vanish. I must be making a mistake in executing this code.
当我运行这段代码时,它让 Helloworld 超链接消失了。我做错了什么?
问题解决:
It is recommended to use a sequence of replace() calls rather than assigning intermediate results and performing replacements sequentially.
你应该将 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.

全部评论 (0)
还没有任何评论哟~
