我正在尝试制作一个简单的页面,最终用户输入一些数字,然后单击按钮查找总数。但是,事情并没有按照我的意愿行事。计算器不仅不起作用,而且只是通过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;
}