随机猜测并计数
1.head first html5 第四章里的一个小例子,我稍微添加了些
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>guss</title> 6 </head> 7 <style> 8 b{ color:red; } 9 10 </style> 11 <body> 12 <script> 13 window.onload=init; 14 function init(){ 15 var click=document.getElementById("click"); 16 click.onclick=gussU; 17 } 18 var guss_count_num=0;//猜测计数 19 var right_count_num=0;//猜对的次数 20 function gussU(){ 21 guss_count_num++; 22 var guss=document.getElementById("guss"); 23 var text=guss.value; 24 var answer=null; 25 26 var answer=["red","green","blue"]; 27 var index=Math.floor(Math.random()*answer.length); 28 29 var tip=document.getElementById("tip"); 30 31 var guss_count=document.getElementById("guss_count"); 32 guss_count.innerHTML=guss_count_num; 33 34 var right_count=document.getElementById("right_count"); 35 36 if(text==answer[index]){ 37 right_count_num++; 38 right_count.innerHTML=right_count_num; 39 tip.innerHTML="You are right I was thinking of <b>"+answer[index]+"</b>"; 40 41 }else{ 42 tip.innerHTML="Sorry I was thinking of <b>"+answer[index]+"</b>"; 43 } 44 var persent=Math.floor((right_count_num/guss_count_num)*100)+"%"; 45 var right_person=document.getElementById("right_persont"); 46 right_person.innerHTML=persent; 47 } 48 49 </script> 50 <p>你要猜的次是:blue,green,red</p> 51 <input type="text" placeholder="guss u" id="guss"> 52 <input type="button" id="click" value="click me"> 53 <p id="tip"></p> 54 <p>你共猜了<em id="guss_count"></em> 次</p> 55 <p>猜对了几<em id="right_count"></em> 次</p> 56 <p>猜测成功率为<em id="right_persont"></em></p> 57 </body> 58 </html>