javascript 替换整个 HTMLinside body 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13011743/
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-26 17:37:58  来源:igfitidea点击:

replacing whole HTMLinside body tag

javascripthtml

提问by user1749030

I want to replace the whole HTML inside bodytag with some content and I use these codes inside both headand bodysections, but in the fist code it doesn't show the content and in the second code it shows the content but doesn't clear ex-content.

我想用一些内容替换body标签内的整个 HTML ,我在headbody部分中使用这些代码,但在第一个代码中它不显示内容,在第二个代码中它显示内容但不清除前内容。

the first code:

第一个代码:

<script>

var content = 'some content';

if(navigator.appName=="Netscape")
{
document.getElementsByTagName('body').innerHTML = content; 
}

</script>

the second code:

第二个代码:

<script>

var content = 'some content';

if(navigator.appName=="Netscape")
{
document.body.innerHTML = content; 
}

</script>

also I use some php code in the document

我也在文档中使用了一些 php 代码

what should I do?
thanks

我该怎么办?
谢谢

回答by Laurence

.getElementsByTagNamereturns an array so you have to use [0]to get the first element:

.getElementsByTagName返回一个数组,因此您必须使用它[0]来获取第一个元素:

<script type="text/javascript">

    var content = 'some content';
    document.getElementsByTagName('body')[0].innerHTML = content; 

</script>

Here is an example: http://jsfiddle.net/MWjsc/

这是一个例子:http: //jsfiddle.net/MWjsc/

回答by San

I believe that you want to display some special content like browser not supported for netscape.

我相信你想显示一些特殊的内容,比如 netscape 不支持的浏览器。

You can use document.writedocument.write(content);this will replace total document content.

您可以使用document.writedocument.write(content);这将替换整个文档内容。