javascript:同一脚本的不同行为

时间:2015-09-19 09:37:17

标签: javascript document.write

我有一些关于javascript行为的问题(我现在正在学习w3schools的javascript),我看过两个带有简单代码的例子,但我不明白为什么代码表现不同: 第一个例子:

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html> 

第二个例子:

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button onclick="document.write(5 + 6)">Try it</button>

</body>
</html>

为什么在第二个示例中,所有文档内容都替换为“11”,并且在第一个示例“11”中附加到文档中?脚本执行时有区别吗?

Ps:我知道这不是问这个问题的合适地方,但是如果你知道更好的书或教程来学习javascript,请把它放在评论中(我是ac #backend开发者和ex android开发者)。

2 个答案:

答案 0 :(得分:5)

这是因为在第一个例子中,浏览器不会自动调用document.open,但是第二个实例。

这是mdn document.write

中的单词
  

如果document.write()调用直接嵌入HTML代码中,   那么它不会调用document.open()。

基本上document.open只清除文档中的所有内容。

查看有关document.writedocument.open的这些文件 mdn document.write
mdn document.open

谢谢伙计!好问题!之前没有注意到这一点。

答案 1 :(得分:0)

文档加载完成后,您无法使用document.write。如果这样做,浏览器将打开一个替换当前文件的新文档。

使用innerHTML属性将HTML代码放在元素中:

 <h1>My First Web Page</h1>
 <p>My first paragraph.</p>
 <span id='r'></span>
 <button id="add"">Try it</button>

JS:

document.getElementById("add").onclick = add;
function add(){
   document.getElementById("r").innerHTML=5+6;
}

http://jsfiddle.net/sharif084/ktx0rmuf/

相关问题