如何获取用户输入并将其输出到网页上

时间:2019-02-19 07:26:13

标签: javascript input output

我正在尝试创建一个程序,要求用户输入两个数字,然后将这两个数字的值相加后输出到网页(显示类似1 + 2 = 3),然后显示这两个数字相乘(1 * 2 = 2)。示例输出应类似于以下内容,但基于从网站用户收到的输入:

1 + 2 = 3

1 * 2 = 2

5 个答案:

答案 0 :(得分:0)

您可以使用input标签获取输入内容,并使用.innerHTML输出到html

function a() {
  document.getElementById("c").innerHTML = Number(document.getElementById("a").value) + Number(document.getElementById("b").value);
}
<input type="number" id="a" />
<input type="number" id="b" onkeyup="a()" />
<div id="c"></div>

答案 1 :(得分:0)

像这样使用prompt

var number1 = parseInt(prompt("Enter a number"));
var number2 = parseInt(prompt("Enter another number"));

document.write(`${number1} + ${number2} = ${number1 + number2}<br>${number1} * ${number2} = ${number1 * number2}`);

答案 2 :(得分:0)

尝试一下

function submit() {
   let test =document.getElementById("text");
   let sum = parseFloat(document.getElementById("firstNumber").value) +parseFloat(document.getElementById("lastNumber").value);
    let mul = parseFloat(document.getElementById("firstNumber").value)  * parseFloat(document.getElementById("lastNumber").value);
   test.innerHTML = document.getElementById("firstNumber").value + ' + ' +document.getElementById("lastNumber").value + " = " +sum +" </br>";
    test.innerHTML += document.getElementById("firstNumber").value + ' * ' +document.getElementById("lastNumber").value + " = " + mul +"\n";
   return true;
}
  First number:<br>
  <input type="number" id="firstNumber" >
  <br>
  Last number:<br>
  <input type="number" id="lastNumber" >
  <br><br>
  <button onclick="return submit();">click</button>


<div id="text"></div>

答案 3 :(得分:0)

这是您的编程水平可能更熟悉的另一种方法,在这种情况下,我们使用输入字段代替提示。

<!DOCTYPE html>
<html>
 <head>
  <script>
    function calc(){
    var num1 = document.getElementById("in1").value;
    var num2 = document.getElementById("in2").value;
    document.getElementsByTagName("p")[0].innerHTML = num1 + "+" + num2 + "=" + (parseInt(num1) + parseInt(num2));
  }
  </script>
 </head>
 <body>

  <input id="in1" type="number"/>
  <input id="in2" type="number"/>

  <button onclick="calc()">Calculate</button>
  <p></p>
 </body>
</html>

答案 4 :(得分:0)

因为它不是我要假设的,所以您要输入用户访问页面的编号,而我正在通过提示请求接收这些输入...

<script>

function init(){
  var input1 = prompt("Please enter the first Number", "First Number");
  var input2 = prompt("Please enter the second Number", "Second Number");

   if (input1 != null && input2 != null) {

     sum = parseInt(input1) + parseInt(input2); 
     str1 = input1 + " + " + input2 + " = " + sum;

     multi = parseInt(input1) * parseInt(input2);
     str2 = input1 + " * " + input2 + " = " + multi;

     document.getElementById("message").innerHTML = str1 + "<br/>" + str2;

    }else{
       alert('...error message');
    }

   }  //end of function...

</script>


<body onload="init()">
  ......    
  <div id="message"></div>
</body>

应该可以正常工作...