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>
元素中的內容。