首页 > 技术文章 > 函数必须绑定事件才可以

zhangjingyun 2015-07-21 10:42 原文

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
 6 <title>练习</title>
 7 <style type="text/css">
 8     div{width: 300px;height: 300px;border:1px solid #ccc;}
 9 </style>
10 <script type="text/javascript">
11 window.onload=function (){
12     document.getElementById('btn').=function (){
13         document.getElementsByTagName('div')[0].style.background='red';
14     }
15 }
16 </script>
17 </head>
18 <body>
19 <input type="button" value="变红" id="btn"/>
20 <div></div>
21 </body>
22 </html>

因为button后面没有对要写的函数绑定事件

解决办法:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
 6 <title>练习</title>
 7 <style type="text/css">
 8     div{width: 300px;height: 300px;border:1px solid #ccc;}
 9 </style>
10 <script type="text/javascript">
11 window.onload=function (){
12     document.getElementById('btn').onclick=function (){
13         document.getElementsByTagName('div')[0].style.background='red';
14     }
15 }
16 </script>
17 </head>
18 <body>
19 <input type="button" value="变红" id="btn"/>
20 <div></div>
21 </body>
22 </html>

 

推荐阅读