按钮功能调用不起作用?

时间:2017-06-09 02:18:54

标签: javascript html

我想要一个类似这样的网页:

欢迎你 [textbox] [textbox] [Multiply!]
输入要乘以的值。

由此HTML代码表示:

window.onload = function begin() {
  document.getElementById("demo").innerHTML = "Welcome";
}

function multiply(var1, var2) {
  document.getElementById('multiply').innerHTML = var1 * var2
}
<body onload="onload();">
  <p id='demo'> </p>

  <form>
    <input type='number' name=num1>
    <input type='number' name=num2>
    <button onclick=multiply(num1, num2)> Multiply! </button>
  </form>

  <p id='multiply'> Enter a value to multiply. </p>

</body>

3 个答案:

答案 0 :(得分:3)

"中缺少onclick,我更改了脚本。我还删除了不必要的元素。只需将它们添加回代码

即可

修改

我返回了<form>代码并添加了type="button"属性,以防止表单提交。感谢 @Patrick Roberts @Nick Tirrell 获取信息

function multiply() {
  var num1 = document.getElementById("num1").value;
  var num2 = document.getElementById("num2").value;
  document.getElementById('multiply').innerHTML = num1 * num2
}
<form>
  <input id="num1" type='number'>
  <input id="num2" type='number'>
  <button type="button" onclick="multiply()"> Multiply! </button>
  <p id='multiply'> Enter a value to multiply. </p>
</form>

答案 1 :(得分:0)

为每个输入提供id属性,然后使用该属性来获取要乘以的值,例如: document.getElementById("my-id-1").value。另外,使用基本的

doc.getElementById("my-button").addEventListener('click', function(evt) {
    //do your thing.
});

答案 2 :(得分:0)

<!DOCTYPE html>
  <html>
    <head>
      <title> Test </title>
    </head>

    <body>
        <form>
          <input type='number' id='num1'>
          <input type='number' id='num2'>
          <button type='button' onclick="multiply()"> Multiply! </button>
        </form>

        <p id='multiply'> Enter a value to multiply. </p>

    <script src="01_using_javascript.js"> </script>
    </body>
</html>

function multiply() {
    var numberOne = document.getElementById('num1').value;
    var numberTwo = document.getElementById('num2').value;
    var multiply = document.getElementById('multiply');
    var multipliedResult = numberOne * numberTwo;
    multiply.innerHTML = multipliedResult;
}