【问题标题】:Javascript eval() input field and output answer in same fieldJavascript eval()输入字段和同一字段中的输出答案
【发布时间】:2018-11-18 18:17:21
【问题描述】:

我正在学习并想知道是否有办法做到这一点,假设我有 HTML 输入字段:

<input type=text id="input">

附近我会有一个按钮:

<button id="equal">=</button>

我想编写 javaScript 来评估该文本字段中的语句(如果它是诸如“2+3”“6/2”等等式),并将该语句替换为该等式的答案。我尝试了什么:

 var equal = document.querySelector("#equal");
 var input = document.querySelector("#input");
 equal.addEventListener('click', function () {
 eval(input.value) += input.innerText;
 });

我已经只输入了 1234567890 和 /*-+ 如果有办法,我将非常感谢解释的答案,最近才开始使用 javaScript,所以它对我来说仍然像一片黑暗的森林,但我确实希望对它有更好的理解。 :)

【问题讨论】:

  • 我建议使用document.getElementById("equal") 而不是document.querySelector("#equal")
  • 你需要input.value = eval(input.value);
  • 一个好的做法是阅读您将要使用的new element 的文档。
  • @liroP 你能解释一下到底有什么区别吗?
  • @ChrisG 谢谢,它有效! :)

标签: javascript html eval


【解决方案1】:

您只需将eval(input.value) += input.innerText 换成input.value = eval(input.value)

var equal = document.querySelector("#equal");
var input = document.querySelector("#input");
equal.addEventListener('click', function() {
  input.value = eval(input.value);
});
<input type=text id="input">
<button id="equal">=</button>

另外,建议使用document.getElementById 而不是document.querySelector,虽然差别不大(主要是与旧浏览器的兼容性)。 Read more

【讨论】:

    【解决方案2】:

    您希望您输入表达式的位置与您显示表达式的位置不同

    <!DOCTYPE html>
    <html>
    <body>
      <button id="evaluate">Get answer</button>
      <input id="input" />
      <p id="result">waiting for answer...</p>
      <script>
        var evaluate = document.getElementById("evaluate");
        var input = document.getElementById("input");
        var result = document.getElementById("result");
        
        evaluate.addEventListener('click', function () {
          try {
            result.textContent = eval(input.value);
          }
          catch (error) {
            result.textContent = "waiting for answer...";
          }
        });
      </script>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 2015-09-07
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 2015-07-13
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多