js中button事件的簡單樣本

來源:互聯網
上載者:User
Code:
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <title></title>  
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  6. <script type="text/javascript">  
  7. window.onload = function(){//頁面所有元素載入完畢  
  8.     var btn = document.getElementById("btn");  //擷取id為btn的元素(button)  
  9.     btn.onclick = function(){                  //給元素添加onclick事件  
  10.         var arrays = new Array();              //建立一個數組對象  
  11.         var items = document.getElementsByName("check");  //擷取name為check的一組元素(checkbox)  
  12.         for(i=0; i < items.length; i++){  //迴圈這組資料  
  13.             if(items[i].checked){      //判斷是否選中  
  14.                 arrays.push(items[i].value);  //把合格 添加到數組中. push()是javascript數組中的方法.  
  15.             }  
  16.         }  
  17.         alert( "選中的個數為:"+arrays.length  );  
  18.     }  
  19. }  
  20. </script>  
  21. </head>  
  22. <body>  
  23. <form method="post" action="#">  
  24.     <input type="checkbox" value="1" name="check" checked="checked"/>  
  25.     <input type="checkbox" value="2" name="check" />  
  26.     <input type="checkbox" value="3" name="check" checked="checked"/>  
  27.     <input type="button" value="你選中的個數" id="btn"/>  
  28. </form>  
  29. </body>  
  30. </html>  

 //這樣也算是實現了 表現層和行為層分離的效果。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.