如何在HTML&#34中打印javascript函数的返回值;添加{x} + {y} = {result}"?

时间:2016-02-04 16:16:26

标签: javascript html

我试图在HTML中打印出x + y的结果,现在它只显示结果,但我希望如下: 添加{x1} + {y} = {result} ??? :/



<html>
  <body>
    
    <br/>
    Enter first number:
    <input type="text" id="txt1" name="text1">
    Enter second number:
    <input type="text" id="txt2" name="text2">
    <p>Click the button to calculate x.</p>
    <button onclick="myFunction()">Try it</button>
    
    <p id="demo"></p>
    
    <script>
      function myFunction() {
	      var result;
        var x = document.getElementById("txt1").value;
        var y = document.getElementById("txt2").value;
        if (isNaN(x) || isNaN(y)){
        	result="enter number!"
        	}
			else{ 
        		result = +x + +y;
        }
        document.getElementById("demo").innerHTML = result;
      }
    </script>
  </body>
</html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您可以创建一个包含变量的字符串:

document.getElementById("demo").innerHTML = x + ' + ' + y + ' = ' + result;

答案 1 :(得分:-1)

&#13;
&#13;
<html>
  <body>
    
    <br/>
    Enter first number:
    <input type="text" id="txt1" name="text1">
    Enter second number:
    <input type="text" id="txt2" name="text2">
    <p>Click the button to calculate x.</p>
    <button onclick="myFunction()">Try it</button>
    
    <p id="demo"></p>
    
    <script>
      function myFunction() {
	      var result;
        var x = document.getElementById("txt1").value;
        var y = document.getElementById("txt2").value;
        if (isNaN(x) || isNaN(y)){
        	result="enter number!"
        	}
			else{ 
        		result = +x + +y;
        }
        document.getElementById("demo").innerHTML = "The addition of " + x + " and " + y + " is " + result;
      }
    </script>
  </body>
</html>
&#13;
&#13;
&#13;