[英]Why is there no output with this javascript code? What am I missing?
這是我寫的一些示例代碼,因為我有一個更難的任務,但現在我什至無法讓它工作。 只是想顯示兩個數字相加的輸出,我錯過了什么?
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<script type="text/javascript">
function Add() {
var n1 = document.getElementById("numOne").value;
var n2 = document.getElementById("numTwo").value;
var total = n1 + n2;
document.getElementById("output").innerHTML = total;
}
</script>
</head>
<body>
<h1>Calc</h1><br />
<form method="post" action="">
NUM 1: <input type="number" name="numOne" id="numOne" /><br />
NUM 2: <input type="number" name="numTwo" id="numTwo" /><br />
<input type="button" value="Add" onclick="ADD()" /><br />
Result: <label id="output"></label>
</form>
</body>
</html>
引用時需要匹配函數名的大小寫。 ADD()
應該是Add()
。 請咨詢您的開發者控制台以獲取錯誤消息。
此外,如果您想對這兩個數字求和,您需要先將它們從字符串中轉換,這樣您就不會執行連接。
function Add() {
var n1 = document.getElementById("numOne").value;
var n2 = document.getElementById("numTwo").value;
var total = parseInt(n1, 10) + parseInt(n2, 10);
document.getElementById("output").innerHTML = total;
}
在這里,我使用基數為10
parseInt()
將數字字符串轉換為數字。
ADD()
=> 更改為Add()
(Javascript 區分大小寫)
Number()
函數將字符串轉換為數字。 完美運行,運行並查看。 (如果你不放這個,你的輸入是5
和6
,那么你的輸出將是56
(字符串連接)而不是11
)
<head> <title>Sample</title> <script type="text/javascript"> function Add() { var n1 = document.getElementById("numOne").value; var n2 = document.getElementById("numTwo").value; var total = Number(n1) + Number(n2); // Number() function document.getElementById("output").innerHTML = total; } </script> </head> <body> <h1>Calc</h1><br /> <form method="post" action=""> NUM 1: <input type="number" name="numOne" id="numOne" /><br /> NUM 2: <input type="number" name="numTwo" id="numTwo" /><br /> <input type="button" value="Add" onclick="Add()" /><br /> Result: <label id="output"></label> </form> </body>
函數名稱區分大小寫,您需要更改:
<input type="button" value="Add" onclick="ADD()" /><br />
對此:
<input type="button" value="Add" onclick="Add()" /><br />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.