如何获取输入字段值JavaScript

时间:2014-02-10 02:24:31

标签: javascript input

我正在尝试创建一个猜谜游戏,如果用户在输入字段中输入数字并单击按钮,则会显示一个文本,说明该数字是大于还是小于JavaScript创建的随机数。我似乎已经弄清楚了其他一切,但我很难获得输入到输入字段的值。

感谢您的帮助。

<div class="wrap" >
 Project: Guessing Game

 <input type="text" name="inputField" value="" id="inputField"/>
 <button id="guess">Guess!</button>
 <br>
 <p id="result"></p>

</div>

<script type="text/javascript" charset="utf-8">

var $ = function(selector) {
    return document.querySelector(selector);
};

var randomRange = function(min,max){
    return Math.random(((Math.random()*(max-min))+min));
};

var randomNumber = randomRange(1,4);

var myButton = $("#guess");

var myNumber = $("#inputField").value;

var myResult = $("#result");

if ( myNumber > randomNumber) {
    myButton.onclick = function () {
    myResult.innerHTML += "Your number is bigger than the random number";
    }
}
else if ( myNumber < randomNumber){
        myButton.onclick = function () {
        myResult.innerHTML += "Your number is smaller than the random number";
    }
}
else if ( myNumber === randomNumber ){
        myButton.onclick = function () {
        myResult.innerHTML += "Your number matches the random number";
    }
}

</script>

2 个答案:

答案 0 :(得分:0)

var $ = function(selector) {
    return document.querySelector(selector);
};
var randomRange = function(min,max){
    return Math.round(((Math.random()*(max-min))+min));//notice here,Math.round
};
var randomNumber = randomRange(1,4);
var myButton = $("#guess");
var myNumber = $("#inputField");
var myResult = $("#result");
myButton.onclick = function(){
    var val = parseInt(myNumber.value, 10);
    if(val < randomNumber){
        //smaller code
    }else if(val > randomNumber){
        //bigger code
    }else{
        //equal code
    }
}

答案 1 :(得分:0)

当没有数据时,您的输入正在被读取,当您单击时,您不会检查数据是否已更改。您应该放置决策块来检查事件处理程序内的输入,如下所示:

myButton.onclick = function () {
    var myNumber = $("#inputField").value;
    myNumber = parseInt(myNumber, 10);
    if ( myNumber > randomNumber) {
        myResult.innerHTML = "Your number is bigger than the random number";
    } else if ( myNumber < randomNumber){
        myResult.innerHTML = "Your number is smaller than the random number";
    } else if ( myNumber === randomNumber ){
        myResult.innerHTML = "Your number matches the random number";
    }
}