编写一个函数来停止重复代码? - JS

时间:2013-05-19 15:17:33

标签: javascript jquery

我正在使用Simpleweather.js插件,它使用JS这样:

$.simpleWeather({
zipcode: '',
woeid: '12289',
location: '',
unit: 'c',
success: function(weather) {
    html = '<h2 class="none">'+weather.city+'</h2>';
    html += '<img src="assets/img/'+weather.code+'.png">';
    html += '<p>'+weather.temp+'&deg; '+weather.units.temp+'<br /><span>'+weather.currently+'</span></p>';
    html += '<p>Wind: '+weather.wind.speed+weather.units.speed+'</p>';
    html += '<div class="tmr"><p>Tomorrow:</p><img src="assets/img/'+weather.tomorrow.code+'.png">'+'<p>'+weather.tomorrow.high+'&deg;'+weather.units.temp+'<br />'+weather.tomorrow.forecast+'</p></div>';
    html += '<a href="'+weather.link+'">Full Forecast</a>';

    $("#weather").html(html);
},
error: function(error) {
    $("#weather").html('<p>'+error+'</p>');
}
});

简单的HTML,例如

<div id="weather"></div> 

显示它。

但是,我想显示多个地方的天气,唯一不同的是woeid,这是一个五位数的数字,以及显示它的div ID,在这里显示为#weather。我想做的是编写一个函数,在调用时,例如:

weatherFunction(divid,woeid);

它将两个作为输入,只是将它们添加到上面的代码中。我之前只在JS编写了非常简单的函数,并且非常希望得到帮助。我在理论上知道怎么做而不是在实践中 - 任何人都可以帮助我或给我一个起点吗?提前干杯!

1 个答案:

答案 0 :(得分:1)

var weatherFunction = function (divid, woeid) {

    $.simpleWeather({
        zipcode: '',
        woeid: woeid,
        location: '',
        unit: 'c',
        success: function(weather) {
            html = '<h2 class="none">'+weather.city+'</h2>';
            html += '<img src="assets/img/'+weather.code+'.png">';
            html += '<p>'+weather.temp+'&deg; '+weather.units.temp+'<br /><span>'+weather.currently+'</span></p>';
            html += '<p>Wind: '+weather.wind.speed+weather.units.speed+'</p>';
            html += '<div class="tmr"><p>Tomorrow:</p><img src="assets/img/'+weather.tomorrow.code+'.png">'+'<p>'+weather.tomorrow.high+'&deg;'+weather.units.temp+'<br />'+weather.tomorrow.forecast+'</p></div>';
            html += '<a href="'+weather.link+'">Full Forecast</a>';

            $(divid).html(html);
        },
        error: function(error) {
            $(divid).html('<p>'+error+'</p>');
        }
    });

}