首页 > 解决方案 > 有没有办法将字符串评估为 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>

你如何解决这个问题?

标签: javascripthtml

解决方案


您需要的功能是 eval().

eval('1+1');
// Output: 2

或在您的代码中实现,即:

var equation = document.getElementById("equation").value;
var answer = document.getElementById("answer");
answer.innerHTML = eval(equation);

有关该eval()功能的更多信息,请阅读文档


推荐阅读