这段代码有什么问题?当我运行它只是显示0作为结果

时间:2016-06-04 19:22:37

标签: javascript

这段代码有什么问题?当我运行它时,只显示0作为结果。我已检查每个已知的可能错误。乘法结果显示为零。

<html>
<head>
<title>Calculate</title>
<style>
</style>
</head>
<body>
<p>1st Number:<input type="text" id="firstNumber"></p>
<p>2nd Number:<input type="text" id="secondNumber"></p>
<button id="m">Multiply</button>
<button id="d">divide</button>
<p id="num"></p>

<script>
 var firstNumber,secondNumber;
 firstNumber=document.getElementById("firstNumber").value;
 secondNumber=document.getElementById("secondNumber").value;

 document.getElementById("m").onclick=function()
 {
  document.getElementById("num").innerHTML=firstNumber*secondNumber;
 }

 document.getElementById("d").onclick=function()
 {
  document.getElementById("num").innerHTML=firstNumber/secondNumber;
 }
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

firstNumbersecondNumber始终为空字符串,因为您会在有人点击之前获取它们。

当有人点击

时,您必须获取值
document.getElementById("m").onclick = function() {
    var firstNumber = document.getElementById("firstNumber").value;
    var secondNumber = document.getElementById("secondNumber").value;

    document.getElementById("num").innerHTML = firstNumber * secondNumber;
}

document.getElementById("d").onclick = function() {
    var firstNumber = document.getElementById("firstNumber").value;
    var secondNumber = document.getElementById("secondNumber").value;

    document.getElementById("num").innerHTML = firstNumber / secondNumber;
}

您最好使用addEventListener代替内联javascript

答案 1 :(得分:1)

在元素上创建变量firstNumbersecondNumber,而不是从函数外部检索值。这样你就可以访问函数内部元素的值。

var firstNumber, secondNumber;
firstNumber = document.getElementById("firstNumber");
secondNumber = document.getElementById("secondNumber");

document.getElementById("m").onclick = function() {
  document.getElementById("num").innerHTML = firstNumber.value * secondNumber.value;
}

document.getElementById("d").onclick = function() {
  document.getElementById("num").innerHTML = firstNumber.value / secondNumber.value;
}
<html>

<head>
  <title>Calculate</title>
  <style>
  </style>
</head>

<body>
  <p>1st Number:
    <input type="text" id="firstNumber">
  </p>
  <p>2nd Number:
    <input type="text" id="secondNumber">
  </p>
  <button id="m">Multiply</button>
  <button id="d">divide</button>
  <p id="num"></p>
</body>

</html>