2

我的作业是使用 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>
4

1 回答 1

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>

希望这可以帮助。

于 2013-11-14T19:43:19.607 回答