我一直得到这个未捕获的TypeError:无法读取未定义的属性'0'
代码完美无缺,控制台或其他任何东西都没有错误,但是一切都会出现这个错误,然后就会消失。有谁知道为什么?
var temp, loc, icon, hum, wind, dir;
var APPID = "56a4fe4f1240df2a9fe267b687a5d191";
function update (weather) {
temp.innerHTML += weather.temp;
loc.innerHTML += weather.loc;
hum.innerHTML += weather.hum;
wind.innerHTML += weather.wind;
dir.innerHTML += weather.dir;
sUp.innerHTML += weather.sUp;
sDown.innerHTML += weather.sDown
icon.src = "//openweathermap.org/img/w/" + weather.icon + ".png";
}
window.onload = function () {
temp = document.getElementById ("t");
loc = document.getElementById ("l");
icon = document.getElementById ("i");
hum = document.getElementById ("h");
wind = document.getElementById ("w");
dir = document.getElementById ("d");
sUp = document.getElementById ("sU");
sDown = document.getElementById ("sD");
if (navigator.geolocation) {
var showPos = function (pos) {
updateLoc (pos.coords.latitude, pos.coords.longitude);
}
navigator.geolocation.getCurrentPosition (showPos);
} else {
var zip = window.prompt("Your location could not be found, please enter your post/zip code.");
updateByZip(zip);
}
}
function updateLoc (lat, long) {
var url = "http://api.openweathermap.org/data/2.5/weather?" +
"lat=" + lat +
"&lon=" + long +
"&APPID=" + APPID;
sendRequest (url);
}
function updateByZip(zip){
var url = "http://api.openweathermap.org/data/2.5/weather?" +
"zip=" + zip +
"&APPID=" + APPID;
sendRequest(url);
}
function sendRequest (url) {
var xmlhttp = new XMLHttpRequest ();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = JSON.parse (xmlhttp.responseText);
var weather = {};
weather.icon = data.weather[0].icon;
weather.dir = direction (data.wind.deg);
weather.wind = mph (data.wind.speed) + "mph";
weather.temp = K2C (data.main.temp) + "°C";
weather.loc = data.name;
weather.hum = data.main.humidity + "%";
weather.sUp = formatDate (data.sys.sunrise);
weather.sDown = formatDate (data.sys.sunset);
update (weather);
}
};
xmlhttp.open ("GET", url, true);
xmlhttp.send ();
}
function K2F (k) {
return Math.round(k * (9 / 5) - 459.67);
}
function K2C (k) {
return Math.round (k - 273.15);
}
function mph (ms) {
return Math.round (ms / 0.44704);
}
function kmph (ms) {
return Math.round (ms * 3.6);
}
function formatDate (t) {
var date = new Date (t * 1000);
var h = date.getHours ();
var m = "0" + date.getMinutes ();
var s = "0" + date.getSeconds ();
return h + ":" + m.substr(-2) + ":" + s.substr(-2);
}
function direction (deg) {
var range = 360 / 16;
var low = 360 - (range / 2);
var high = (low + range) % 360;
var angles = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"];
for (var i in angles) {
if (deg >= low && deg < high) {
return angles[i]
}
low = (low + range) % 360;
high = (high + range) % 360;
}
return "N";
}