Yan' Blog

关于document.write()的一点新发现

1.如果是在页面输入document.write("aaaaaa"),那么会在放document.write的地方输出aaaaaa
2.在Onload事件里,或script标签加defer="defer",则会覆盖,那么整个页面就变成了输入的内容
3.新发现:在IE浏览器(firefox正常)无法输出
满足这两个条件:
<1>延时加载   <2>动态加载一个js文件,在这个文件里作写入操作
eg:
test.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>测试document.write</title>
</head>
<body>
陆羽《茶经》
一之源
二之具
三之造
四之器
五之煮
六之饮
七之事
八之出
九之就
十之图
<script language='javascript'>
//加载文件
function Script_Include()
{
    var jsPost = document.createElement("script");
jsPost.setAttribute("language","javascript",true)
jsPost.setAttribute("src","1.js",true);
document.body.appendChild(jsPost);
}
window.setTimeout("Script_Include()",2000);
</script>
</body>
</html>
1.js:
document.write("okokokokokokokokok!")

如果这样则可以:
test.html
<script language='javascript'>
//加载文件
function Script_Include()
{
//1
    document.write("okokokokokokokokok");

//2
var s = "<script language=javascript>document.write(\"I LOve YOU\");</scr"+"ipt>"
eval("document.write('"+ s + "')");

}
window.setTimeout("Script_Include()",2000);
</script>

或是手动的操作写入:
test.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>测试document.write</title>
</head>
<body>
<div id="AId">陆羽《茶经》</div>

<script language='javascript'>
//加载文件
function Script_Include()
{
    var jsPost = document.createElement("script");
jsPost.setAttribute("language","javascript",true)
jsPost.setAttribute("src","1.js",true);
document.body.appendChild(jsPost);
}
window.setTimeout("Script_Include()",2000);
</script>
</body>
</html>
1.js
//给div标签加click事件,在点击的时候写入
document.getElementById("AId").onclick = function ()
{
document.write("test")
}

综上所述,IE把它作为一种安全机制在延时加载时调用外部文件无法写入,试想,如果可以的话,那么我们打开浏览器开始很正常,过段时间(延时)页面就被安全修改(document.write),那岂不是很糟糕!

posted on 2008-12-11 10:14  xxyzjb  阅读(680)  评论(0)    收藏  举报

导航