javascript 猜数字游戏程序

来源:岁月联盟 编辑:exp 时间:2012-03-20

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
        <title>Insert title here</title>
        <script type="text/javascript">
                 /*
                * 先加载窗体
                * 生成一个1-100之间的随机数
                * 获取按钮
                * 获取text的value
                * 当点击按钮时,用text的value和随机数比较
                *
                */
               window.onload = function(){
                var num = Math.floor(Math.random() * 100 + 1);
                var button = document.getElementById("button");
       var times = 0;
                button.onclick = function(){
                 var text = document.getElementById("inputText");
                 var value = text.value;
                 if(++times > 3){
         alert("您不适合玩此类游戏");
         return;
        }
                 if(isNaN(value)){
                  alert("您输入的不是一个数字,请输入一个数字!");
                 }else if(value < 1 || value > 100){
                  alert("请输入一个1-100的数字");
                 }else if(value == num){
                  alert("您猜对了!")
                 }else if(value > num){
                  alert("大了");
                 }else{
                  alert("小了");
                 }
        text.value = "";
                }
               }
        </script>
    </head>
    <body>
        请输入一个1-100的整数: <input type="text" id="inputText"> <input type="button" id="button" value=" 猜猜猜 ">
    </body>
</html>

 

摘自  代俊建的专栏