在Javascript函数中传递对象

Passing objects in Javascript function

本文关键字:对象 Javascript 函数      更新时间:2023-09-26

不确定我是否在以下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 

应该是:

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

(无分号)

去掉那个分号:

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

这里有一个使用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/