您现在的位置是:首页 > 电脑技术查询 > web开发

那里错了啊 帮小弟我看看

编辑:chaxungu时间:2022-10-02 23:15:42分类:web开发

那里错了啊 帮我看看啊
<html>
<head>
<title>1111</title>
<script>
var bt=document.getElementById("but1");
bt.attachEvent("onclick",fy);
function fy(){
alert("点击了一下");
}
</script>
</head>

<body>

<input type="button" id="but1" value="点击" />

</body>
</html>
为什么提示bt为空或不是对象啊

------解决方案--------------------
下面dom还没加载呢,怎么会有but1元素,要在页面dom加载完成后再调用
var bt=document.getElementById("but1");
或者把这些js放到该元素的下面执行。

------解决方案--------------------
HTML code<html><head><title>1111</title><script>window.onload = function(){ var bt=document.getElementById("but1"); bt.attachEvent("onclick",fy);}function fy(){alert("点击了一下"); } </script></head><body><input type="button" id="but1" value="点击" ></body></html>
------解决方案--------------------
HTML code<html><head> <title>1111</title> </head><body><input type="button" id="but1" value="点击" /><script> var bt=document.getElementById("but1"); bt.attachEvent("onclick",fy); function fy(){ alert("点击了一下"); } </script></body></html>
------解决方案--------------------
javascript版:
HTML code<html><head><title>1111</title><script type="text/javascript">function ClickEvent(){var bt=document.getElementById("but1");bt.attachEvent("onclick",fy);}function fy(){alert("点击了一下");}window.onload=ClickEvent;</script></head><body><input type="button" id="but1" value="点击" /></body></html>