Javascript在页面中的位置究竟怎样影响其执行顺序? PS:我就把错误代码的<a href="#" id="link1">hello,world</a>和<script>……</script>对调了一下位置~ 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 你的JavaScript代码在<a href="#" id="link1">hello,world</a>载入之前运行就得不到stringout = document.getElementById('link1');这种简单的情况下,你可以考虑用给window对象的load事件附加一个在页面载入后触发的函数,这样就可以不考虑位置了。比如:<!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=gb2312" /> <title>无标题文档 </title> <script type="text/javascript">window.onload=test; var i = 1; function DoIt( ) { message="\n for the "+i+" times,hello,world "; document.Form1.Text1.value+=message; i++; }function test(){ var stringout = document.getElementById('link1'); stringout.onclick = DoIt;} </script></head> <body> <a href="#" id="link1">hello,world </a> <form name="Form1"> <textarea name="Text1" cols="60" rows="20"> this is a test for the stringout!</textarea> </form> </body> </html> var stringout = document.getElementById('link1'); stringout.onclick = DoIt;你那段错的原因在这里.这段是已经执行了的,而 document.getElementById('link1');为空.~~所以会出错.修改后那段因为文档已经加载,所以在执行var stringout = document.getElementById('link1'); stringout.onclick = DoIt;就没错 太谢谢了。吼吼,但是你在这句话中“你可以考虑用给window对象的load事件附加一个在页面载入后触发的函数”应该是onload,扣你一分,吼吼,别生气啊~ window对象的load事件我指的是事件的名称。比如,mouse对象的mouseover事件也是。在绑定事件时,如果是用传统的方式,就像我上面写的,或者是IE的绑定,事件名称才要在前面加on的如果是W3C的DOM绑定,就是直接用事件名称的。比如:window.addEventListener('load', function(){ … }, false); 在原有基础上增加jquery验证小数值文本框 求助 ie8下JS无法预览图片 求助 js 单击 tr td 可以进行显示或隐藏 变换? JS字符替换问题 网页实现在多首歌曲连放 如何能让一个页面先执行一段<script>代码再加载页面内容 window.createPopup()的一些问题 [在线等]请问论坛帖子列表的前面的+号展开是怎么做的? 这个网页元素checkbox我怎么访问?急! 如何调用另一个页面的元素? javascript拖拽表格并按顺序提交
就得不到stringout = document.getElementById('link1');
这种简单的情况下,你可以考虑用给window对象的load事件附加一个在页面载入后触发的函数,这样就可以不考虑位置了。
比如:
<!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=gb2312" />
<title>无标题文档 </title>
<script type="text/javascript">
window.onload=test;
var i = 1;
function DoIt( )
{
message="\n for the "+i+" times,hello,world ";
document.Form1.Text1.value+=message;
i++;
}
function test(){
var stringout = document.getElementById('link1');
stringout.onclick = DoIt;}
</script>
</head>
<body>
<a href="#" id="link1">hello,world </a>
<form name="Form1">
<textarea name="Text1" cols="60" rows="20"> this is a test for the stringout!</textarea>
</form>
</body>
</html>
stringout.onclick = DoIt;
你那段错的原因在这里.这段是已经执行了的,而 document.getElementById('link1');为空.~~所以会出错.修改后那段因为文档已经加载,所以在执行
var stringout = document.getElementById('link1');
stringout.onclick = DoIt;
就没错
我指的是事件的名称。
比如,mouse对象的mouseover事件也是。
在绑定事件时,如果是用传统的方式,就像我上面写的,或者是IE的绑定,事件名称才要在前面加on的
如果是W3C的DOM绑定,就是直接用事件名称的。
比如:window.addEventListener('load', function(){ … }, false);