怎么样来控制html文件dom文件加载完毕后js脚本才执行

luyue15 2012-05-09 02:10:11
小弟又来讨教了。。
貌似出现了喝昨天问题不一样的东西
例子很简单:
页面代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>新窗口打开一个页面</title>
<script type="text/javascript" src="http://s.syyx.com/nycs/js/jquery-1.4.2.min.js"></script>
<script src="script/script07.js" language="javascript" type="text/javascript" </script>
</head>

<body bgcolor="#FFFFFF">
<div align="center">
<h1>Let's Play the Windows</h1>
<h2>
<a href="#" id="openWin"> open a new window </a>
<br/>
<a href="#" id="closeWin">close a new window</a>
</h2>
</div>

</body>
</html>

script07.js中的JS代码

// JavaScript Document


window.onlaod=newWinLinks;
var newWindow=null;
alert(document.links.length);
function newWinLinks()
{
for (var i=0;i<document.links.length;i++)
{
document.links[i].onclick=chgWindowState;
alert("111111");
}
}

function windowOpen()
{
if(newWindow && ! newWindow.closed)
{
return true;
}
return false;
}

function chgWindowState()
{
if(this.id == "closeWin")
{
if(windowOpen())
{
newWindow.close();
}
else
{
alert("This window is already open!");
}
}
if(this.id == "openWin")
{
if(windowOpen())
{
alert("The window is already open");
}
else
{
newWindow = window.open("","newWin","toolbar,location=yes,width=300,height=200");
}
}
return false;
}



现在的效果是 显示links数是0 应该是2的
自然也就没有进入alert("11111");这里
小弟 觉得是dom文档没有加载完全的原因
因为小弟在html文档末位添加
alert(document.links.length);明显显示的2


问下 怎么解决JS 判断DOM文档加载完毕以后才执行JS代码啊
...全文
907 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
sd1232123 2012-05-09
  • 打赏
  • 举报
回复
document.ready()
乌镇程序员 2012-05-09
  • 打赏
  • 举报
回复
就用window.onload

JS是解释型语言,加载和执行都是按照在html文档中出现的顺序来加载执行的。就你的代码来说,不管你的js代码是直接写在html文档中还是外部JS文件中,由于书写的位置是在head标签中,总比body标签中的元素更早加载到DOM树中,加载到alert(document.links.length);这一行代码时就会马上执行,此时body中的元素都还没有加载,弹出的链接数量当然是0。
2012-05-09
  • 打赏
  • 举报
回复
window.onlaod 这个写错了,是onload
2012-05-09
  • 打赏
  • 举报
回复
window.onlaod=newWinLinks;

你不是有这个吗? onload就是dom加载完成后再执行的

87,910

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧