javascript - 在 JavaScript 中更改字体颜色时出现问题

标签 javascript html

我正在构建一个计算器,并且必须使其每次按下操作按钮时字体都会变成红色。

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/

相关文章:

javascript - angular2-google-maps 模态问题

javascript - 隐藏/显示表单(复选框表单)-- javascript

javascript - 使用 Safari 在本地下载 blob

javascript - 使用 javascript 交换图像

javascript - 添加 javascript 代码后容器之间的空白

html - 如何在 Html 中使用内联 block 显示表格和图像?

html - Adblock plus - 隐藏部分 css 样式或更改类名?

javascript - 使用 canvas 和 p5.js 移动正方形

javascript - 将一些数据提取到其中后,使文本框只读

python - 改进 python 代码片段