我的作业是使用JavaScript代码构建一个HTML页面,以便从用户那里获取当前的天气状况,并根据天气输出推荐值。我想我已正确编写代码,但我的代码不会向文本字段输出任何内容。相反,Chrome会向我显示以下错误消息:Uncaught TypeError: object is not a function
。我不明白这个错误。这是代码。谢谢你能给我的任何帮助。
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Weather Recommendation</title>
<script type="text/JavaScript">
function weather() {
//Get the user input
var condition = document.weather.condition.value;
//Choose the output
var output;
if (condition == "snow") {
output = "go south";
}
else if (condition == "rain") {
output = "don't forget your umbrella";
}
else if (condition == "wind") {
output = "don't forget your jacket";
}
else if (condition == "fog") {
output = "don't drive";
}
else if (condition == "sun") {
output = "skip school, go hiking";
}
//Display the output
document.weather.recommendation.value = output;
}
</script>
</head>
<body>
<form name="weather">
Weather condition <input type="text" name="condition" size="8"><br>
<button type="button" onclick="weather()">Recommendation</button>
<input type="text" name="recommendation" readonly>
</form>
</body>
</html>
答案 0 :(得分:1)
@ Pietu1998是正确的。当你调用weather()时,它试图访问表单名称。我不确定为什么,但更改名称就行了。
<script type="text/javascript">
function yourWeather() {
//Get the user input
var condition = document.weather.condition.value;
//Choose the output
var output;
if (condition == "snow") {
output = "go south";
}
else if (condition == "rain") {
output = "don't forget your umbrella";
}
else if (condition == "wind") {
output = "don't forget your jacket";
}
else if (condition == "fog") {
output = "don't drive";
}
else if (condition == "sun") {
output = "skip school, go hiking";
}
//Display the output
document.weather.recommendation.value = output;
}
</script>
</head>
<body>
<form name="weather">
Weather condition <input type="text" name="condition" size="8"><br>
<button type="button" onclick="yourWeather()">Recommendation</button>
<input type="text" name="recommendation" readonly>
</form>
希望这有帮助。