javascript - 有没有办法将字符串评估为 HTML/JS 中的数学表达式?
问题描述
所以我有这段代码用于计算器,当我在文本框中输入一些东西时,它只显示未定义。当我输入像 1+1 这样的数学表达式时,我需要它,它会显示 2。你可以在我的网站上看到它的实际效果:G1blue.github.io/gencal.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Calculator: General (Under maintenance)</title>
<style>
h1{
font-size: 100px;
margin: auto;
}
div {
font-size: 100px;
position: absolute;
top: 150px;
}
</style>
</head>
<button><a href="index.html">Go to home</a></button>
<body>
<h1>Calculator: General</h1>
<input oninput="varChange()" id="equation" type="number">
<div id="answer"></div>
<script>
function varChange(){
var equation = document.getElementById("equation").value;
var answer = document.getElementById("answer");
answer.innerHTML = new Function(equation)()
}
</script>
</body>
</html>
你如何解决这个问题?
解决方案
您需要的功能是 eval()
.
eval('1+1');
// Output: 2
或在您的代码中实现,即:
var equation = document.getElementById("equation").value;
var answer = document.getElementById("answer");
answer.innerHTML = eval(equation);
有关该eval()
功能的更多信息,请阅读文档。
推荐阅读
- python - 使用 groupby 函数根据唯一条件从不同列中选择不同的值
- sql-server - EDGE 浏览器无法呈现报告 - 与 IE 和 Chrome 一起使用时
- react-native - 如何在 React 中使用 highcharts 的 chart.get(location)?
- flutter - 如何解决flutter firebase auth中的网络错误?
- python - 如何计算总和为给定值的值的倍数?
- sql - 聚合函数的算术加法
- java - Java 8 流条件检查
- linux - 监视 Linux 中的复制和粘贴操作
- javascript - fullcalendar.js v4 - 如何在标题中设置 html?
- c# - 使用 ObservableAsPropertyHelper 激活/停用