0

我的网站上有大约 15 份以下代码。唯一改变的是 url、经度、纬度和标记变量标题。我怎样才能把它切碎并减少重复?

$.ajax({
    url: "http://api.wunderground.com/api/<api_key>/conditions/q/pws:KCASANFR128.json",
    dataType: "jsonp",
    success: function(parsed_json) {
    var location = parsed_json['current_observation']['observation_location']['city'];
    var temp_f = parsed_json['current_observation']['temp_f'];
    var weather = parsed_json['current_observation']['weather'].toLowerCase();
    var iconUrl = parsed_json['current_observation']['icon_url'];
    var iconPic = new MyIcon(iconUrl);
    var markerRichmond = new L.Marker(new L.LatLng(37.779806, -122.471895), {icon: iconPic});
    markerRichmond.bindPopup("Current temperature in " +location+ " is: " +temp_f+ " and it is " + weather);
    map.addLayer(markerRichmond);
}});
4

2 回答 2

1

您可以创建一个函数来接收这些变量并将它们提供给 ajax 调用。然后你只需要这个 ajax 块的一个副本,你可以通过调用getWeather函数来调用它

function getWeather(url, lat, long, title){
    $.ajax({
        url: url,
        dataType: "jsonp",
        success: function(parsed_json) {
            var location = parsed_json['current_observation']['observation_location']['city'];
            var temp_f = parsed_json['current_observation']['temp_f'];
            var weather = parsed_json['current_observation']['weather'].toLowerCase();
            var iconUrl = parsed_json['current_observation']['icon_url'];
            var iconPic = new MyIcon(iconUrl);
            var markerRichmond = new L.Marker(new L.LatLng(lat, long), {icon: iconPic});
            markerRichmond.bindPopup(title);
            map.addLayer(markerRichmond);
        }
    });
}

我不确定我在这里是否正确处理了标题,但你明白了。如果您对标题可能如何更改有所了解,我可以相应地修复代码。

希望这可以帮助。

于 2012-06-07T17:16:12.307 回答
0
var current_observation = parsed_json['current_observation'];

这也缩短了解析的次数。然后你可以将你的变量称为

current_observation['observation_location']['city'];
于 2014-11-04T17:16:14.303 回答