0

问题:为什么我不能将输入文本的值#userGuess放入变量中userInput

这是HTML

    <div class="row-fluid">
    <div class="span12" style="text-align:center">
        <form>
            <fieldset>
                <legend>Guessing Game</legend>
                <label>Input a number in your mind</label>
                <input type="text" id="userGuess" auto-complete="off">
                <span class="help-block" style="display:block">
                    <p class="help-block" id="resultWaiting" style="display:block">Results!</p>
                    <p class="help-block" id="resultWarmer" style="display:none; color:#E61010">Warmer!</p>
                    <p class="help-block" id="resultColder" style="display:none; color:#104CE6">Brr! Colder</p>
                    <p class="help-block" id="resultCorrect" style="display:none; color:#E61010">YES! YOU GOT IT</p>    
                </span>
                <button type="submit" id="submitButton" class="btn">Submit</button>
                <button class="btn btn-danger" type="button">Show Result</button>
            </fieldset>
        </form> 
    </div>
</div>

这是javascript代码

    $("#submitButton").click(submit);
function submit() {
    var userInput = $('#userGuess').val();
    if (userInput == pcRandom) {
        $("#resultWaiting").css("display","none");
        $("#resultCorrect").css("display","block");
    } else{
        compare(userInput, pcRandom);
    }
}

在 Chrome 开发工具上调试时,它只是说 userInput 变量是未定义的。

我将 Bootstrap 用于 css 框架和 jQuery

4

1 回答 1

1

在我将 a 添加event.preventDefault()到 jQuery 之后,这对我有用。但是,这是假设compare比较两个猜测并相应地更改 CSS,然后pcRandom选择一个随机数:

$("#submitButton").click(function(event) {
    event.preventDefault();
    submit();
});

function submit() {
    var userInput = $('#userGuess').val();
    var pcRandom = 5;
    console.log(userInput);
    if (userInput == pcRandom) {
        $("#resultWaiting").css("display","none");
        $("#resultCorrect").css("display","block");
    } else{
        compare(userInput, pcRandom);
    }
 }

编辑:

这是一个功能齐全的 JSFiddle:http: //jsfiddle.net/9VYvg/

于 2013-10-30T23:30:55.450 回答