我正在构建一个计算器,必须这样做,以便每次单击操作员按钮时,字体都会变为红色。
function changeBtnColor(entry){
if(entry == '+'){
calculator.getElementById("buttonAdd").style.fontcolor = 'red';
calculator.answer.value +=' + ';
}
if(entry == '-'){
calculator.getElementById("buttonSub").style.fontcolor = 'red';
calculator.answer.value +=' - ';
}
if(entry == '*'){
calculator.getElementById("buttonMult").style.fontcolor = 'red';
calculator.answer.value +=' * ';
}
if(entry == '/'){
calculator.getElementById("buttonDiv").style.fontcolor = 'red';
calculator.answer.value +=' / ';
}
}
我如何调用此js函数的示例是:
<form id = "calculator" name=”calculator”>
<table id = "myTable" border = "2">
<tbody>
<tr>
<td colspan = "4">
<input id = "answer" type="text" name="answer"/>
</td>
</tr>
<tr>
<td><input id = "button7" type="button" value="7" onClick="calculator.answer.value +='7'"></td>
<td><input id = "button8" type="button" value="8" onClick="calculator.answer.value +='8'"></td>
<td><input id = "button9" type="button" value="9" onClick="calculator.answer.value +='9'"></td>
<td><input id = "buttonAdd" type="button" value="+" onClick="changeBtnColor('+')"></td>
</tr>
执行此操作时,出现错误:
calculator.getElementById is not a function
at changeBtnColor (calculator.js:44)
at HTMLInputElement.onclick (calculator.html:21)
有人对此错误有任何建议或可以告诉我为什么发生此错误吗?谢谢!
答案 0 :(得分:2)
函数“ getElementById”是为文档对象而不是表单元素定义的。
document.getElementById("buttonAdd")