js實現點擊不同的按鈕后各自返回被點擊的次數
一、總結
1、注意:返回的不是三個按鈕總的點擊數,而是每一個的
2、用全局變量的話每一個按鈕要多一個函數,用閉包就很方便
二、js實現點擊不同的按鈕后各自返回被點擊的次數
練習3:
- 實例描述:點擊按鈕后自動彈出按鈕被累計點擊的次數
- 案例要點:
理解閉包的基本用法。
三、代碼
截圖
注意:返回的不是三個按鈕總的點擊數,而是每一個的
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>練習03</title> 6 <style type="text/css"> 7 input{ 8 width: 150px; 9 height: 80px; 10 border-radius: 10px; 11 font-size: 24px; 12 padding: 10px; 13 background: green; 14 outline: none; 15 } 16 </style> 17 </head> 18 <body> 19 <input type="button" value="按鈕A" onclick="countA()"> 20 <input type="button" value="按鈕B" onclick="countB()"> 21 <input type="button" value="按鈕C" onclick="countC()"> 22 <script> 23 //方案1 大於兩個時候比較繁瑣 24 var counter=0; 25 var counter2=0; 26 function count1(){ //1、全局變量適合做返回所有按鈕的總點擊數,否則用全局變量的話每一個按鈕要多一個函數,用閉包就很方便 27 counter+=1; 28 alert('您共點擊了我'+counter+'次') 29 } 30 function count2(){ 31 counter2+=1; 32 alert('您共點擊了我'+counter2+'次') 33 } 34 //方案2 35 function count() { 36 var counter = 0; 37 function increment() { 38 counter += 1; //2、閉包實現原理:這個匿名函數用了外面函數的變量,外面函數的變量被常駐內存,有幾個匿名函數,匿名函數中用的的這個變量就有多少個在內存, 39 alert('您共點擊了我'+counter+'次'); 40 } 41 return increment 42 } 43 var countA=count(); 44 var countB=count() 45 var countC=count() 46 47 48 // function count() { 49 // var counter = 0; 50 // (function () { 51 // return(function(){ 52 // counter += 1; 53 // alert('您共點擊了我'+counter+'次'); 54 // } 55 // )() 56 // })() 57 // } 58 </script> 59 </body> 60 </html>