DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> js簡單抽獎代碼
js簡單抽獎代碼
編輯:關於JavaScript     

核心:js的Math對象和Array對象

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>random</title>
 <style>
  #awardListDom{width: 100%;}
 </style>
</head>
<body>
 <label for="awardListDom">獎項列表</label><br>
 <input type="text" value="" id="awardListDom"> <br>
 <label for="num">抽到的獎</label><br>
 <input type="text" value="" id="num"> <br>
 <button id="submit">開始抽獎</button>
 <script>
  /* 
  * 思路:隨機抽獎,抽一個獎項便減少一個
  * Math 對象方法:http://www.w3school.com.cn/jsref/jsref_obj_math.asp
  *  -random():返回 0 ~ 1 之間的隨機數。
  *  -floor():獲取整數
  * 數組操作:
  *  - splice(x,y); x:起始位置, y:獲取並刪除個數
  */

  function random(min,max){
    return Math.floor(min+Math.random()*(max-min));
  }
  var awardListDom=document.getElementById("awardListDom"),
  num=document.getElementById("num"),
  submit=document.getElementById("submit");
  var awardList=["一等獎","二等獎","二等獎","三等獎","三等獎","三等獎","鼓勵獎","鼓勵獎","鼓勵獎","鼓勵獎","謝謝參與","謝謝參與","謝謝參與","謝謝參與","謝謝參與","謝謝參與"];

  awardListDom.value=awardList;
  submit.onclick=function(){
   //引用數組
   var oldArray=awardList;
   var rNum=random(0,oldArray.length);
   
   if(oldArray.length<1){
    awardListDom.value="活動結束";
    num.value="活動結束";
   }
   else{
    num.value=oldArray[rNum];
    oldArray.splice(rNum,1);
    awardListDom.value=oldArray;
   }
  }
 </script>
</body>
</html>

demo:http://demo.jb51.net/js/2015/choujiang/

github:https://github.com/litengdesign/award

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved