首页 > 解决方案 > 如何用新的输入 -java 脚本替换文本框中的内容

问题描述

我正在创建一个在线计算器,但是当用户在文本框中输入他们的方程式时遇到问题,我可以在控制台日志中评估和显示方程式,但是我无法用答案替换方程式。如果单击“=”,它应该评估文本框中的方程式并将方程式替换为答案。这就是我到目前为止所拥有的。

 const equalsButton = document.querySelector('input[value="="]').onclick = function(){
    var inputVar = document.querySelector('[name=equation]').value
   
    console.log(eval(inputVar));
    return false;
  }

标签: javascript

解决方案


由于您没有提供html代码,并且由于您使用eval了 - 请查看此演示以获取简单的计算器:

let total = []; // this will hold the arguments 
const equalsButton = document.querySelectorAll('input'); // calculator buttons 
for (var i = 0; i < equalsButton.length; i++) { // iterate the buttons
    equalsButton[i].addEventListener('click', function() { // listen to click 
        document.querySelector('#result').textContent += this.value; // add the clicked value to the screen
        if (this.value === '=') { // if equal clicked - show result
            document.querySelector('#result').textContent = eval(total.join('')); // result would be calculated from the total array arguments
        }        
        else { // any other clicked buttons
            total.push(this.value); // would be add to the array that would be the result when '=' would be clicked
        }
    });
}   
<div id="result" style="font-size: larger;"></div>
<div>
    <input type="button" value="0">
    <input type="button" value="1">
    <input type="button" value="2">
    <input type="button" value="3">
    <input type="button" value="4">
    <br>
    <input type="button" value="5">
    <input type="button" value="6">
    <input type="button" value="7">
    <input type="button" value="8">
    <input type="button" value="9">
    <br>
    <input type="button" value="+">
    <input type="button" value="-">
    <input type="button" value="/">
    <input type="button" value="*">
    <input type="button" value="=">
</div>


推荐阅读