javascript 按钮点击事件

    

这个部分主要来讲解一下按钮点击事件的集中js的实现方式:

方法一:

[html]  view plain  copy
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head lang="en">  
  4.     <meta charset="UTF-8">  
  5.     <title>test1</title>  
  6.     <script>  
  7.         function buttonClick(){  
  8.             alert("你点击了按钮哦");  
  9.         }  
  10.     </script>  
  11. </head>  
  12. <body>  
  13. <input  id="button" type="button" value="点击" onclick="buttonClick();">  
  14. </body>  
  15. </html>  

方法二:

[html]  view plain  copy
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head lang="en">  
  4.     <meta charset="UTF-8">  
  5.     <title>test1</title>  
  6.   
  7. </head>  
  8. <body>  
  9. <input  id="button" type="button" value="点击" >  
  10. <script>  
  11.     var btn = document.getElementById("button");  
  12.     btn.onclick =function(){  
  13.         alert("你点击了按钮哦!");  
  14.     }  
  15. </script>  
  16. </body>  
  17. </html>  

对于方法二,一定要把script代码块写在body的尾部,但是如果说硬是要写在head标签内的话,一定要在window.load里面,或者在jq的另一种写法$(document).ready()。 如下方代码所示。这个是代码执行顺序的原因。

[html]  view plain  copy
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head lang="en">  
  4.     <meta charset="UTF-8">  
  5.     <title>test1</title>  
  6.   
  7.     <script>  
  8.         window.onload = function(){  
  9.             var btn = document.getElementById("button");  
  10.             btn.onclick =function(){  
  11.                 alert("你点击了按钮哦!");  
  12.             }  
  13.         }  
  14.     </script>  
  15. </head>  
  16. <body>  
  17. <input  id="button" type="button" value="点击" >  
  18. </body>  
  19. </html>  
方法三:

[html]  view plain  copy
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head lang="en">  
  4.     <meta charset="UTF-8">  
  5.     <title>test1</title>  
  6.     <script>  
  7.         window.onload = function(){  
  8.             var btn = document.getElementById("button");  
  9.             btn.addEventListener('click',function() {alert('你点击了按钮哦!')},false);  
  10.         }  
  11.     </script>  
  12. </head>  
  13. <body>  
  14. <input  id="button" type="button" value="点击" >  
  15. </body>  
  16. </html>  
  • 12
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值