documen.write 和 innerHTML 的区别?

document.write只能重绘整个页面,innerHTML可以重绘页面的一部分。

1. ducument.write使用举例
html文档:

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题</title>
<script type="text/javascript" src="js.js"></script>
</head>
<body>
<p>原有内容</p>
<div id="testdiv">原有内容</div>
</body>
</html>

js文档:

window.onload = function() {
    document.write("现有内容");
}

执行结果显示:document.write会将页面上的所有内容清除包括标题。

2. innerHTML使用举例
html文档:

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题</title>
<script type="text/javascript" src="js.js"></script>
</head>
<body>
<p>原有内容</p>
<div id="testdiv">原有内容</div>
</body>
</html>

js文档:

window.onload = function() {
var testdiv=document.getElementById('testdiv');
testdiv.innerHTML = "<p>I love <em>JavaScript</em>!</p>";
}

执行结果显示:innerHTML只会重写所属元素的内容,即<div>元素中的内容。







原文地址:https://www.cnblogs.com/Rivend/p/12613296.html