这段代码有什么问题?当我运行它时,只显示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>
答案 0 :(得分:1)
firstNumber
和secondNumber
始终为空字符串,因为您会在有人点击之前获取它们。
当有人点击
时,您必须获取值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)
在元素上创建变量firstNumber
和secondNumber
,而不是从函数外部检索值。这样你就可以访问函数内部元素的值。
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>