<!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>
</head><body>
<form name="form">
<input type="button" name="b1" id='b1' value="text" /> <script language="javascript">
var b1 = document.getElementById('b1');
/* 其中$str变量可以为你服务器返回的变量*/$str = 'hello world';if(b1.attachEvent){ //MSIE 方法
b1.attachEvent("onclick", function(){alertMsg($str)});
}else if(b1.addEventListener){ // W3C方法
b1.addEventListener('click',function(){ alertMsg($str)});
}function alertMsg(s){
alert(s);
}</script> </form>
</body>
</html>我的问题是:如果吧javascript代码放在head区,不会出现任何效果
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head><body>
<form name="form">
<input type="button" name="b1" id='b1' value="text" /> <script language="javascript">
var b1 = document.getElementById('b1');
/* 其中$str变量可以为你服务器返回的变量*/$str = 'hello world';if(b1.attachEvent){ //MSIE 方法
b1.attachEvent("onclick", function(){alertMsg($str)});
}else if(b1.addEventListener){ // W3C方法
b1.addEventListener('click',function(){ alertMsg($str)});
}function alertMsg(s){
alert(s);
}</script> </form>
</body>
</html>我的问题是:如果吧javascript代码放在head区,不会出现任何效果
var b1 = document.getElementById('b1');
是获取不到对象的,你可以把这段代码放在onload事件中,页面load之后在执行
window.onload = function(){
var b1 = document.getElementById('b1');
/* 其中$str变量可以为你服务器返回的变量*/$str = 'hello world';if(b1.attachEvent){ //MSIE 方法
b1.attachEvent("onclick", function(){alertMsg($str)});
}else if(b1.addEventListener){ // W3C方法
b1.addEventListener('click',function(){ alertMsg($str)});
}function alertMsg(s){
alert(s);
}
}
</script>
这样就能放head里面了
放在head,上面这行会出错.因为解析到head,DOM树还没创建完成!找不到b1
var b1 = document.getElementById('b1');
b1就没有
b1没有下面就没有意义
所以一般 dom 绑定的都放在body的onload事件里面