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>  

猜你喜欢

转载自blog.csdn.net/ftd1314/article/details/80530366