为什么document.write没有按预期完成

时间:2012-03-18 04:00:34

标签: javascript jquery

只是尝试设置一个小测试页面,即使它没有按预期运行。

给出以下工作代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8">
<title>Terry's Test Page</title>
<script src='jquery-1.7.1.min.js'></script>
</head>
<body>
    <p>from the html in index.html</p>
</body>
</html>

我得到了我所期望的,标签标签中的html和Terry的测试页面中的一行。但是,如果我在</head>行之前添加:

<script>$(document).ready(function() {
document.write('<p>from the js</p>');
});
</script>

我正确地得到了'来自js'行 - 没有来自html,因为document.write取代了它 - 但是标签标签没有填满Terry的测试页面。在IE中,标签标签显示了网址,在Firefox中它显示了“正在连接...”但它永远不会超出这个范围。

我不明白的document.write是什么?我是否必须发出某种文件结尾或某些文件?

2 个答案:

答案 0 :(得分:3)

由于您在网页加载后致电document.write,因此会调用document.open,这会清空整个文档。浏览器尽力而为,并根据您提供的内容创建一个完整的新文档。该文档不仅是body中的内容,还包括其他所有内容。

在您的情况下,您的文档为<p>from the js</p>,但由于这不是有效的HTML文档(缺少htmlheadbody),因此浏览器会添加什么是必要的。

例如,参加

document.write('<head><title>foo</title></head>');

这只会创建一个空的body,但会将页面标题设置为foo

答案 1 :(得分:2)

document.write不再广泛使用,特别是对于jQuery。您应该使用append或insert。也就是说,它确实有效,但不推荐:http://jsbin.com/upamem

相关问题