在Javascript函数中传递对象

时间:2013-08-28 21:36:05

标签: javascript html html5

不确定我是否在以下javascript代码中获取了正确的对象:

<form>
    What is 5 + 5?: <input type ="number" id ="num_answer;"/>
</form>
<script>
    function basic_math(){
        var num_val = document.getElementById('num_answer').value;
        if (num_val == 10) {
            document.getElementById('num_answer').style.backgroundColor = green;
        }
        else{
            document.getElementById('num_answer').style.backgroundColor = red;
        }
    }
</script>


<button type = "button" onclick ="basic_math();"> Solve! 
</button>

我得到的错误:

    Uncaught TypeError: Cannot read property 'value' of null 

3 个答案:

答案 0 :(得分:2)

摆脱那个分号:

What is 5 + 5?: <input type ="number" id ="num_answer;"/>
<!--                              This is a typo     ^           -->

答案 1 :(得分:2)

应该是:

<input type ="number" id="num_answer"/>

(无分号)

答案 2 :(得分:1)

这是一个使用JQuery的解决方案

<p> <span> What is 5 + 5? </span> 
  <input type="number" id="num_answer" />    </p>    

function basic_math()
{   
   num_val = $("#num_answer").val();
   if (num_val == 10) {
    $('#num_answer').css("color", "white");
    $('#num_answer').css("background-color", "green");
   } else {

     $('#num_answer').css("background-color", "red");

     }
}

http://jsfiddle.net/fonsecat/WMJh3/17/