简体   繁体   English

使用JavaScript进行计算

[英]making a calculation using JavaScript

Why this isn't working? 为什么这不起作用? I also did this by assigning the result back to the input field but that didn't work and still this is not showing an alert which should show the result.. 我还通过将结果分配回输入字段来完成此操作,但这没有用,仍然没有显示应显示结果的警报。

    <script type="text/javascript">
    function calculate() {
       var calculateit=document.getElementById('disp');
       var pluscharacter=/+/;
       var matchplus=calculateit.search(pluscharacter);
       var inputlength=calculateit.length;
           if(matchplus!=-1 && matchplus!=0 matchplus!=inputlength) {
              answer=calculateit[0]+calculateit[1];
              alert("Your answer is: "+answer+" Is it?");
    }
    }
    </script>

Your if statement isn't a valid condition. 您的if陈述式无效。 Try: 尝试:

if(matchplus!=-1 && matchplus!=0 && matchplus!=inputlength)
var calculateit = document.getElementById('disp');
var matchplus = calculateit.search(pluscharacter);

calculateit is a Node doesn't have any search() method. calculateit是一个Node ,没有任何search()方法。

You're doing stuff you don't need to do - just split the string. 您正在做不需要做的事情-只需拆分字符串即可。 You also need to get the innerHTML - THAT's the string. 您还需要获取innerHTML-这就是字符串。 Or you can get the "value" from an input field instead. 或者,您也可以从输入字段获取“值”。 I'd trim it to get rid of the white space around the equation, though the parseInt would take care of that as well. 我会修剪它以消除方程式周围的空白,尽管parseInt也可以解决这一问题。 I'd also push the answer into another div. 我也将答案推到另一个div。 Here's a jsfiddle: 这是一个jsfiddle:

https://jsfiddle.net/mckinleymedia/9ezky35v/2/ https://jsfiddle.net/mckinleymedia/9ezky35v/2/

With this HTML: 使用此HTML:

<h3>Equation</h3>
<div id="disp">12+12</div>
<h3>Answer</h3>
<div id="answer"></div>

You can use this script: 您可以使用以下脚本:

function calculate() {
  var calculateit = document.getElementById('disp').innerHTML.trim(),
      numbers = calculateit.split('+'),
      answerDiv = document.getElementById('answer');
  if ( numbers.length > 1 ) {
    answer = parseInt(numbers[0]) + parseInt(numbers[1]);
    answerDiv.innerHTML = "Your answer is: <b>" + answer + "</b>, Right?";
  } else {
    answerDiv.innerHTML = "I can't calculate that equation.";
  }
}
calculate();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM