0

. 大家好,我正在尝试将教程作为页面中的一个模块来实现,但我收到“weatherData.temperature is null”错误。

我以前遇到过“weatherData.city is null”错误,但通过在 js 上使用 onreadystatechange 修复了它。

我在收到错误之前就知道了,因为我试图将 setInnerHTML 设置为空值,因为我没有将脚本包装在 onreadystatechange 中,但现在我很困惑为什么我会因为不同的错误而遇到类似的错误行代码。

如果有人能告诉我我做错了什么,将不胜感激!太感谢了!

(是的,由于我无法控制的原因,我无法将页面上的 html 和 js 分开。我知道。我知道......)

HTML:

<div id="weather-web-app">
    <section>
        <h1 id="city">Weather Web App</h1>
        <p>
            <a href="temperature" href="#" onclick="switchUnits(); return false;" title="Click to switch between metric and imperial units">
            </a>
            <span id="weather">
                Current temperature and weather conditions
            </span>
        </p>
    </section>

</div>

JS

<script>
document.onreadystatechange = function(){
    var weatherData = {
        city:               document.querySelector("#city"),
        weather:            document.querySelector("#weather"),
        temperature:        document.querySelector("#temperature"),
        temperatureValue:   0,
        units:              "°C"
    };

    function switchUnits(){
        if (weatherData.units == "°C"){
            weatherData.temperatureValue = weatherData.temperatureValue * 9/5 + 32;
            weatherData.units = "°F";
        } else {
            weatherData.temperatureValue = (weatherData.temperatureValue - 32) * 5/9;
            weatherData.units = "°C";
        }

        weatherData.temperature.innerHTML = weatherData.temperatureValue + weatherData.units + ", ";      
    }

    function getLocationAndWeather(){
        if (window.XMLHttpRequest){
            var xhr = new XMLHttpRequest();
            xhr.addEventListener("load", function() {
                var response = JSON.parse(xhr.responseText);

                console.log(response);
                var position = {
                    latitude:   response.latitude,
                    longitude:  response.longitude
                };
                var cityName = response.city;

                var weatherSimpleDescription    = response.weather.simple;
                var weatherDescription          = response.weather.description;
                var weatherTemperature          = response.weather.temperature;

                weatherData.temperatureValue = weatherTemperature;

                loadBackground(position.latitude, position.longitude, weatherSimpleDescription);

                weatherData.city.innerHTML          = cityName;
                weatherData.weather.innerHTML       = ", " + weatherDescription;
                weatherData.temperature.innerHTML   = weatherTemperature + weatherData.units;
            }, false);

            xhr.addEventListener("error", function(err){
                alert("Could not complete the request");
            }, false);

            xhr.open("GET", "https://fourtonfish.com/tutorials/weather-web-app/getlocationandweather.php?owapikey=YOUROPENWEATHERMAPKEY&units=metric", true);
            xhr.send();
        } else {
            alert("Unable to fetch location and weather data.");
        }           
    }

    function loadBackground(lat, lon, weatherTag) {
        var script_element = document.createElement('script');

        script_element.src = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=YOURFLICKRAPIKEY&lat=" + lat + "&lon=" + lon + "&accuracy=1&tags=" + weatherTag + "&sort=relevance&extras=url_l&format=json";

        document.getElementsByTagName('head')[0].appendChild(script_element);
    }

    function jsonFlickrApi(data){
        if (data.photos.pages > 0){
            var photo = data.photos.photo[0];
            document.querySelector("body").style.backgroundImage = "url('" + photo.url_l + "')";
            document.querySelector("#image-source").setAttribute("href", "http://www.flickr.com/photos/" + photo.owner + "/" + photo.id);
        } else {
            document.querySelector("body").style.backgroundImage = "url('https://fourtonfish.com/tutorials/weather-web-app/images/default.jpg')";
            document.querySelector("#image-source").setAttribute("href", "https://www.flickr.com/photos/superfamous/310185523/sizes/o/");
        }
    }

    getLocationAndWeather();
}
</script>
4

1 回答 1

1

您可能需要检查readyState您的onreadystatechange.

document.onreadystatechange = function () {
    if (document.readyState === "interactive") {

        // ...

        getLocationAndWeather();
    }
};

示例:document.readyState


你也需要改变

<a href="temperature" 

<a id="temperature" 

要开始switchUnits跑步,您需要

switchUnits = function switchUnits () {
    if (weatherData.units == "°C"){
        weatherData.temperatureValue = weatherData.temperatureValue * 9/5 + 32;
        weatherData.units = "°F";
    } else {
        weatherData.temperatureValue = (weatherData.temperatureValue - 32) * 5/9;
        weatherData.units = "°C";
    }

    weatherData.temperature.innerHTML = weatherData.temperatureValue + weatherData.units + ", ";      
};

...因此该功能发布到window.

于 2014-12-16T17:40:23.390 回答