这个部分主要来讲解一下按钮点击事件的集中 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>
就爱阅读 www.92to.com 网友整理上传, 为您提供最全的知识大全, 期待您的分享,转载请注明出处。
来源: