[英]why document.write doesn't complete as expected
Just trying to set up a little test page and even it doesn't behave as expected. 只是尝试设置一个小的测试页,即使它的表现也不如预期。
Given the following working code: 给出以下工作代码:
<!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>
I get what I expect, the one line from the html and Terry's Test Page in the tab label. 我得到了我所期望的,标签标签中的html和Terry's Test Page中的一行。 However, if I add just before the
</head>
line: 但是,如果我在
</head>
行之前添加:
<script>$(document).ready(function() {
document.write('<p>from the js</p>');
});
</script>
I properly get the 'from the js' line -- no from html since document.write replaces it -- but the tab label is not filled with Terry's Test Page. 我正确地从js行中获取了html,因为document.write替换了html,所以没有从html行中获取,但是选项卡标签未填充Terry的测试页。 In IE the tab label shows the url, in Firefox it shows 'Connecting ...' but it never gets beyond that.
在IE中,标签标签显示网址,而在Firefox中,标签显示“正在连接...”,但它永远不会超出该范围。
What is it about document.write that I don't understand? 我不了解的document.write是什么? Do I have to issue some sort of end of file or some such?
我是否必须发出某种文件结尾或类似的结尾?
Since you call document.write
after page load, it calls document.open
, which empties the whole document. 既然你调用
document.write
页面加载后,它会调用document.open
,其清空整个文档。 The browser does its best and creates a complete new document with what you provide. 浏览器会尽力而为,并使用您提供的内容创建一个完整的新文档。 The document is not only the content in the
body
, but everything else as well. 文档不仅是
body
的内容,还包括其他所有内容。
In your case, your document is <p>from the js</p>
, but since this is not a valid HTML document (missing html
, head
and body
), the browser will add what's necessary. 对于您而言,您的文档是
<p>from the js</p>
,但是由于这不是有效的HTML文档(缺少html
, head
和body
),因此浏览器将添加必要的内容。
For example take 例如拿
document.write('<head><title>foo</title></head>');
This will just create an empty body
, but set the title of the page to foo
. 这只会创建一个空的
body
,但是将页面的标题设置为foo
。
document.write
is no longer widely used, especially with jQuery. document.write
不再被广泛使用,尤其是在jQuery中。 You should use append or insert instead. 您应该使用追加或插入。 That said, it does work, but it's not recommended: http://jsbin.com/upamem
也就是说,它确实有效,但是不建议使用: http : //jsbin.com/upamem
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.