JavaScript 中可以在点击事件上绑定函数, 点击时执行函数, 通过统计函数执行次数来统计点击次数.
JavaScript 中统计点击次数:
- <!DOCTYPE html>
- <HTML>
- <head>
- <title>
- Document
- </title>
- <style>
- #Odiv{ margin:0 auto; width: 200px; height:200px; background: yellow;
- }
- </style>
- </head>
- <body>
- <div id="Odiv" onclick="show()">
- 点击 0 次
- </div>
- <script>
- var time = 0;
- function show() {
- if (time % 2 == 0) {
- Odiv.style.background = "pink";
- console.log(time);
- time++;
- } else {
- Odiv.style.background = "yellow";
- console.log(time);
- time++;
- }
- document.getElementById('Odiv').innerHTML = "点击" + time + "次";
- }
- </script>
- </body>
- </HTML>
实现效果如下:
JavaScript 点击事件的写法:
第一种:
- btn.onclick=function(){
- alert('hello world');
- }
第二种:
- btn.addEventListener('click',function(){
- alert('hello world')
- },false);
- btn.addEventListener('click',function(){
- alert(this.id)
- },false);
第三种:
- function demo(){
- alert('hello');
- }
- <button id="btn" onclick="demo()">click</button>
来源: http://www.css88.com/qa/javascript/11604.html