Javascript - 尽管使用 onreadystatechange 仍然出现空错误 [英] Javascript - Getting null error despite using onreadystatechange

查看:36
本文介绍了Javascript - 尽管使用 onreadystatechange 仍然出现空错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.大家好,我正在尝试实施 this 教程作为页面中的一个模块,但我收到weatherData.temperature is null"错误.

我之前一直收到weatherData.city is null"错误,但通过在 js 上使用 onreadystatechange 修复了它.

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

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

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

HTML:

<部分><h1 id="city">天气网络应用</h1><p><a href="温度" href="#" onclick="switchUnits(); return false;"title="单击可在公制和英制单位之间切换"></a><span id="天气">当前温度和天气状况</span></p></节>

JS

解决方案

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

document.onreadystatechange = function () {如果(document.readyState ===交互式"){//...getLocationAndWeather();}};

示例:document.readyState

<小时>

你也需要改变

<小时>

要运行 switchUnits,您需要

switchUnits = function switchUnits() {if (weatherData.units == "°C"){天气数据.温度值 = 天气数据.温度值 * 9/5 + 32;weatherData.units = "°F";} 别的 {天气数据.温度值 = (天气数据.温度值 - 32) * 5/9;WeatherData.units = "°C";}weatherData.temperature.innerHTML = weatherData.temperatureValue + weatherData.units + ", ";};

...所以函数被发布到window.

. Hello y'all, I'm trying to implement this tutorial as a module in a page but I am getting a "weatherData.temperature is null" error.

I had previously been getting a "weatherData.city is null" error but fixed it by using onreadystatechange on the js.

I get that before I was getting the error because I was trying to setInnerHTML to something that was null because I hadn't wrapped the script in the onreadystatechange but now I'm stumped as to why I'm getting a similar error for a different line of code.

If anyone could tell me what I'm doing wrong it would be very much appreciate! Thank you so much!

(And yes, for reasons beyond my control I cannot separate the html and js on the page. I know. I know...)

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>

解决方案

You likely need to check the readyState in your onreadystatechange.

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

        // ...

        getLocationAndWeather();
    }
};

Sample: document.readyState


Also you need to change

<a href="temperature" 

to

<a id="temperature" 


To get switchUnits running, you'll need

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 + ", ";      
};

... so the function is published to the window.

这篇关于Javascript - 尽管使用 onreadystatechange 仍然出现空错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆