[英]Passing objects in Javascript function
不知道我是否在以下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
摆脱该分号:
What is 5 + 5?: <input type ="number" id ="num_answer;"/>
<!-- This is a typo ^ -->
它应该是:
<input type ="number" id="num_answer"/>
(无分号)
这是使用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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.