我正在尝试添加自动刷新到这个代码块可以有人为我纠正这个请事需要整理这个项目 这是我到目前为止的代码
<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));
}
}
});
});
}
});
});
}
});
答案 0 :(得分:2)
您的描述有点令人困惑,但据我所知您尝试每6秒运行一次getLocation()函数。如果是这种情况,那么不要只在$(document).ready()函数中调用getLocation(),而是使用您的函数调用setInterval()。
$(document).ready(function () {
getLocation();
setInterval(getLocation(), 6000);
}
你还应该从getLocation()函数中删除对setInterval()的调用,因为它会将函数设置为每次运行时每6秒调用一次。