我正在尝试向此代码块添加自动刷新功能,有人可以为我更正此吗,请先汇总该项目,谢谢
这是我到目前为止得到的代码
<script src="js/jquery.js"></script>
<script>
$(document).ready(function() {
getLocation();
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + position.coords.latitude + "," + position.coords.longitude + "&sensor=true";
//var url ="http://maps.googleapis.com/maps/api/geocode/json?latlng=43.428852, -80.472206&sensor=true";
$(document).ready(function() {
$.get(url, function(data, status) {
//console.log(data)
if (data == null) {
alert("")
} else {
var city = data.results[2].formatted_address;
document.getElementById("cityname").innerHTML = city;
var country = "cd";
var url2 = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22" + city + "%2C%2" + country + "l%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
$(document).ready(function() {
$.get(url2, function(data, status) {
if (data == null) {
alert("Error, No Weather Report in this location")
} else {
//console.log(data)
var results = data.query.results;
if (results == null) {
alert("Error, No Weather Report in this location")
} else {
var location = data.query.results.channel.location;
var forecasts = data.query.results.channel.item.forecast;
var code = data.query.results.channel.item.condition.code;
if (code >= 3 && code <= 16) {
//rain
document.getElementById("myimage").src = "images/rain.png";
} else if (code >= 26 && code <= 30) {
//cloudy
document.getElementById("myimage").src = "images/clouds.png";
} else if (code >= 31 && code <= 32) {
//sun
document.getElementById("myimage").src = "images/sun.png";
} else if (code >= 33 && code <= 34) {
//fair
document.getElementById("myimage").src = "images/forecast.png";
} else {
//Nill
}
document.getElementById("myweathertext").innerHTML = data.query.results.channel.item.condition.text;
document.getElementById("weathernow").innerHTML = toCelsius(data.query.results.channel.item.condition.temp) + "°<span>C<span>";
setInverval(getLocation, 6000);
//console.log(toCelsius(data.query.results.channel.item.condition.temp));
}
}
});
});
}
});
});
}
});
最佳答案
您的描述有些混乱,但是据我了解,您正在尝试每6秒运行一次getLocation()函数。如果是这种情况,那么不仅要在$(document).ready()函数中一次调用getLocation(),还要使用函数调用setInterval()。
$(document).ready(function () {
getLocation();
setInterval(getLocation(), 6000);
}
您还应该从getLocation()函数中删除对setInterval()的调用,因为它将设置该函数在每次运行时每6秒调用一次其自身。
关于javascript - 如何在JavaScript中自动刷新天气预报,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43551584/