javascript - 如何用新的输入 -java 脚本替换文本框中的内容
问题描述
我正在创建一个在线计算器,但是当用户在文本框中输入他们的方程式时遇到问题,我可以在控制台日志中评估和显示方程式,但是我无法用答案替换方程式。如果单击“=”,它应该评估文本框中的方程式并将方程式替换为答案。这就是我到目前为止所拥有的。
const equalsButton = document.querySelector('input[value="="]').onclick = function(){
var inputVar = document.querySelector('[name=equation]').value
console.log(eval(inputVar));
return false;
}
解决方案
由于您没有提供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>
推荐阅读
- momentjs - 无法使用 MomentJS 将日期字符串转换为所需格式
- python - Tkinter RSS Feed 滚动(从左到右)
- google-cloud-platform - BigQuery python 客户端使用 Streaming API 删除一些行
- c# - 如何理解不受 IO 限制的异步代码
- laravel - Laravel 多态多对多关系
- javascript - 我可以在 (function($){...}(jQuery)); 中使用 Ajax 提交请求吗?
- c - 警告 C4244:'function':从 'time_t' 转换为 'unsigned int',可能丢失数据'
- jenkins - 失败时在不同的奴隶上重新运行 Jenkins 作业
- android - 如何从我的应用程序中正确识别 AnkiDroid(或任何其他外部应用程序)的文件存储目录?
- upgrade - Xcart 应用升级包时出现错误