我正在尝试在我的大学Javascript课程中完成这个项目。 据我所知,我的逻辑是合理的,但我没有做正确的事情,也无法弄清楚出了什么问题?...................... .................................................. .................................................. .................................................. .................................................. .................................................. ..............................................
function monthAsString(num){
var months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
return months[num-1];
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Textfield to Textfield</title>
<script src="DateUDFs.js"></script>
<script>
/*
Write a function called getMonth() that passes the
month number entered by the user to the monthAsString()
function in DateUDFs.js and writes the result in
the monthName field.
*/
function getMonth() {
var elementMonthNumber = document.getElementById('monthNumber');
var elementMonthName = document.getElementById('monthName');
var month = monthAsString(elementMonthNumber.value);
elementMonthName.value = month;
window.onload = function() {
document.getElementById('getmonthbutton').addEventListener('click', getMonth , false);
}
}
// pseudo code
// When the document loads grab the button and add a click event listener,
//on click call the get month function.
// In the get month function.
//
// Grab the input field then grab the output field.
// Pass the value of the input field to the monthAsString function.
// Set the value of the output field to be = to the string value of the input value.
</script>
</head>
<body>
<h1>Month Check</h1>
<form name="dateForm">
Month Number: <input type="text" name="monthNumber" id="monthNumber" size="2">
<input type="button" value="Get Month" id="getmonthbutton"><br>
Month Name: <input type="text" name="monthName" id="monthName" size="10">
</form>
</body>
</html>
答案 0 :(得分:1)
现在您可以获得月份编号。 您正在从脚本标记中添加javascript代码,这是不正确的。
function monthAsString(num){
var months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
return months[num-1];
}
window.onload = function() {
const elementMonthNumber = document.getElementById('monthNumber');
const elementMonthName = document.getElementById('monthName');
document.getElementById('getmonthbutton').addEventListener('click', getMonth);
function getMonth() {
let monthNumber = elementMonthNumber.value;
console.log(monthNumber); //the monthNumber is displayed
//now try to display the month name since it's a homework
//and if you get stuck just comment
}
}
&#13;
<h1>Month Check</h1>
<form name="dateForm">
Month Number: <input type="text" name="monthNumber" id="monthNumber" size="2">
<input type="button" value="Get Month" id="getmonthbutton"><br>
Month Name: <input type="text" name="monthName" id="monthName" size="10">
</form>
&#13;