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

标签 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 中,选项卡标签显示 url,在 Firefox 中,它显示“正在连接...”,但它永远不会超出此范围。

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

最佳答案

既然你调用 document.write 页面加载后,它调用 document.open ,它清空了整个文档。浏览器会尽力而为,并使用您提供的内容创建一个完整的新文档。文档不仅是body中的内容, 但其他一切也是如此。

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

举个例子

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

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

关于javascript - 为什么 document.write 没有按预期完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9755878/

相关文章:

jquery 改变变换(rotateY)

javascript - 如何引用 Angular 值,以便引用不会在缩小时被破坏

javascript - 如何使用 react 在 jquery 中添加 props 函数

jquery - AJAX 到 Ruby Controller

javascript - 使用主题标签打开页面时平滑滚动到 div

令人头疼的javascript循环字符串比较

javascript - 组件 DOM 未更新 | Angular 通用

javascript - 将一个网站嵌入另一个网站

javascript - Laravel 不在函数中接受参数

单击按钮并运行 $.ajax 函数时,php mysql 不保存数据