我正在嘗試SAMS Teach Yourself Learn JavaScript in 21 Days 中的以下練習;
“查看清單 7.1 并對其進行修改,以便使用 XHTML 表單輸入數字而不是使用提示框。”
清單 7.1 如下;
<html>
<head>
<title>Precision of numbers</title>
<script type="text/javascript" language="javascript">
<!--
function Calculate(){
var n = 10.0 / 3.0;
document.write("10.0 divided by 3.0 is " n);
}
-->
</script>
</head>
<body onload="Calculate()">
</body>
</html>
這是我的嘗試,但我只是要放置 JS 腳本和表單片段;
<script type="text/javascript" language="javascript">
<!--
function SetFocus(){
document.Precision.FirstInput.focus();
}
function Calculate(){
var num1 = parseInt(document.getElementById('FirstInput').value);
var num2 = parseInt(document.getElementById('SecondInput').value);
if (isNaN(num1) || isNaN(num2){
alert("You made an invalid entry. Please start again.");
document.SimpleForm.reset();
SetFocus();
}
else{
var result document.getElementById('result').value = num1 / num2;
}
}
-->
</script>
和html表單
<form name="Precision">
<p>
<strong>Enter first number:</strong>
<input type="text" name="FirstInput" id="FirstInput" />
</p>
<p>
<strong>Enter second number:</strong>
<input type="text" name="SecondInput" id="SecondInput" />
</p>
<p>
<strong>The answer is:</strong>
<input type="text" name="result" id="result" />
</p>
<p>
<button onclick="Calculate()">Click here to calculate</button>
</p>
</form>
我的問題是按鈕沒有執行該功能,我想知道為什么。
uj5u.com熱心網友回復:
我已經修復了您的代碼并添加了一些注釋以獲得更多解釋!
function SetFocus() {
document.Precision.FirstInput.focus();
}
function Calculate() {
var num1 = parseInt(document.getElementById("FirstInput").value);
var num2 = parseInt(document.getElementById("SecondInput").value);
if (isNaN(num1) || isNaN(num2)) {
// add closed parenthesis
alert("You made an invalid entry. Please start again.");
document.Precision.reset(); // target Precision form not SimpleForm!?
SetFocus();
} else {
document.getElementById("result").value = num1 / num2;
}
}
<body onload="SetFocus()">
<!-- when the page load set focus to first input -->
<form name="Precision">
<p>
<strong>Enter first number:</strong>
<input type="text" name="FirstInput" id="FirstInput" />
</p>
<p>
<strong>Enter second number:</strong>
<input type="text" name="SecondInput" id="SecondInput" />
</p>
<p>
<strong>The answer is:</strong>
<input type="text" name="result" id="result" />
</p>
<p>
<button onclick="Calculate()" type="button">
<!-- add type="button" to prevent form a page from reload -->
Click here to calculate
</button>
</p>
</form>
</body>
旁注:
- 這
<!-- -->是一個 HTML 注釋標記。 - Javascript 多行注釋,以正斜杠開頭,后跟星號 (
/*),以星號結尾,后跟正斜杠 (*/)。
內部script標簽您JS不寫HTML,因此您將(/**/)用于評論不是HTML(<!-- -->)使用的標簽。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/469214.html
標籤:javascript html 按钮 计算 划分
上一篇:Firebase存盤承諾未解決
