我正在构建一个计算器,并且必须使其每次按下操作按钮时字体都会变成红色。
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)
有人对这个错误有任何建议或者可以告诉我为什么会发生吗?谢谢!
最佳答案
函数“getElementById”是为文档对象定义的,而不是为表单元素定义的。
document.getElementById("buttonAdd")
关于javascript - 在 JavaScript 中更改字体颜色时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52582483/