这个部分主要来讲解一下按钮点击事件的集中js的实现方式:
方法一:
- <!DOCTYPE html>
- <html>
- <head lang="en">
- <meta charset="UTF-8">
- <title>test1</title>
- <script>
- function buttonClick(){
- alert("你点击了按钮哦");
- }
- </script>
- </head>
- <body>
- <input id="button" type="button" value="点击" onclick="buttonClick();">
- </body>
- </html>
方法二:
- <!DOCTYPE html>
- <html>
- <head lang="en">
- <meta charset="UTF-8">
- <title>test1</title>
- </head>
- <body>
- <input id="button" type="button" value="点击" >
- <script>
- var btn = document.getElementById("button");
- btn.onclick =function(){
- alert("你点击了按钮哦!");
- }
- </script>
- </body>
- </html>
对于方法二,一定要把script代码块写在body的尾部,但是如果说硬是要写在head标签内的话,一定要在window.load里面,或者在jq的另一种写法$(document).ready()。 如下方代码所示。这个是代码执行顺序的原因。
- <!DOCTYPE html>
- <html>
- <head lang="en">
- <meta charset="UTF-8">
- <title>test1</title>
- <script>
- window.onload = function(){
- var btn = document.getElementById("button");
- btn.onclick =function(){
- alert("你点击了按钮哦!");
- }
- }
- </script>
- </head>
- <body>
- <input id="button" type="button" value="点击" >
- </body>
- </html>
- <!DOCTYPE html>
- <html>
- <head lang="en">
- <meta charset="UTF-8">
- <title>test1</title>
- <script>
- window.onload = function(){
- var btn = document.getElementById("button");
- btn.addEventListener('click',function() {alert('你点击了按钮哦!')},false);
- }
- </script>
- </head>
- <body>
- <input id="button" type="button" value="点击" >
- </body>
- </html>