我正在尝试制作一个简单的页面,最终用户在其中输入一些数字并单击按钮以查找总数。但是,事情并没有按照我的意愿进行。不仅计算器不起作用,而且通过 JavaScript 简单地添加指令也不起作用。
我究竟做错了什么?
HTML:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Assignment 5 | Variables, Functions, and Loops</title>
</head>
<body>
<section class="greeting_area">
</section>
<br>
<br>
<!-- BEGIN FORM -->
<form action="" method="get" name="assignment_form" id="assignment_form">
<!-- FIRST NUMBER -->
<label for="first_number">First Number:</label>
<input type="number" name="first_number" id="first_number" autofocus required />
<!-- FIRST NUMBER -->
<!-- HOW TO CALCULATE -->
<select name="calculate_with">
<option value="add">+</option>
<option value="subtract">-</option>
<option value="multiply">x</option>
<option value="divide">÷</option>
</select>
<!-- HOW TO CALCULATE -->
<!-- SECOND NUMBER -->
<label for="second_number">Second Number:</label>
<input type="number" name="second_number" id="second_number" required />
<!-- SECOND NUMBER -->
<!-- RESULT TEXT BOX -->
<label for="result">= </label>
<input type="text" name="result" id="result" />
<!-- RESULT TEXT BOX -->
<br>
<!-- CALCULATE BUTTON -->
<button id="calculate_button"></button>
<!-- CALCULATE BUTTON -->
</form>
<!-- END FORM -->
</body>
<script src="scripts/calculator.js"></script>
</html>
JavaScript:
// This anonymous function adds a greeting and instructions to the DOM
(function ()
{
// Official variable-declaring spot
var targetArea = document.getElementsByTagName("section");
// Create a <p> element for our greeting
var paragraph = document.createElement("p");
// Create the actual greeting
var greeting = document.createTextNode("GREETING");
// Insert the greeting into the DOM
targetArea.appendChild(greeting);
// Create an entry into the DOM
var button = document.getElementById("calculate_button");
// This function adds an EventListener to the 'Calculate' button
button.addEventListener("click", function calculateSomeNumbers()
{
// Place all variable declarations here
var resultTextBox = document.getElementById("result");
var firstNumber = document.getElementById("first_number").value;
var secondNumber = document.getElementById("second_number").value;
var result = calculateButton(firstNumber, secondNumber);
// Place the result into the "result" text box
resultTextBox.value = result;
}, false);
// We're calling the calculateButton function
}
)();
// This function holds the execution of clicking the 'Calculate' button to calculate the numbers
function calculateButton(firstNumber, secondNumber)
{
// Declare a variable to hold the result
var result = 0;
// Calculate!
result = firstNumber + secondNumber;
// Return the result to the calculateSomeNumbers function
return result;
}