// 任务 // 1: 第二次打开app,请求的数据还是上一次的城市数据 (function(bom,dom) { // 自执行函数 // js 模拟类 // this 指向 function Weather() { this.cityList = ['合肥','蚌埠','六安','铜陵','黄山']; this.localCity = []; this.BaseUrl = { index: 'http://127.0.0.1:3000/weather/index' }; this.init() } Weather.prototype = { init: function () { this.getCityName() this.getCityList() this.get("合肥", (res) => { this.RenderingPage(res) }); }, getCityName() { var self = this,len = 0; $(".search input").on("input", function () { if( $(this).val().length < len) { $(".search_tips").empty() } self.cityList.forEach((value,index,city) => { if ($(this).val() == value) { $(".search_tips").empty() $(".search_tips").append(`

${value}

`) len = $(this).val().length; self.CityNameClick() } }); }) }, CityNameClick() { var self = this; $(".search_tips p").on("click", function() { // 如果是第一次打开app使用 localCity 数组存放数据然后set进localStorage if (localStorage.getItem("city") == null) { self.localCity.push($(this).text()) localStorage.setItem("city",JSON.stringify(self.localCity)) } else { // 如果第二次使用app,先读本地已经有的 city,然后将新的城市添加进去,最后set进localStorage var lcoal = JSON.parse(localStorage.getItem("city")) lcoal.push($(this).text()) localStorage.setItem("city",JSON.stringify(lcoal)) } self.get($(this).text(), function(res){ self.RenderingPage(res) $.closePanel() }) }) }, RenderingPage(data) { var future = data.future var sk = data.sk var today = data.today $(".fg_title").text(today.city); // 当前温度 $(".top_number").text(`${sk.temp}°`) // 温度下面的信息 $(".top_bottom").text(`${sk.wind_direction} | ${sk.wind_strength} | ${sk.humidity}`) // 构造一个新的今天的天气数组 var weather_list = [today.weather,today.temperature,sk.wind_strength,sk.wind_direction,sk.humidity,today.uv_index]; // 将今天的详细数据遍历到 weather_info 的 li上 $(".weather_info ul li").each(function(index){ $(this).find("p").text(weather_list[index]); }); $(".weather_list ul").empty(); // 通过 forEach 遍历未来7天的数据构造成li标签,然后依次追加到 weather_list ul 中 future.forEach(function(value,index,arr){ $(".weather_list ul").append(`
  • ${value.week}

    ${value.weather}

    ${value.temperature.substring(0,3)} ~ ${value.temperature.substring(4)}
  • `) }); $.hideIndicator() }, getCityList() { var self = this; $(".open-city").on("click", function() { var list = JSON.parse(localStorage.getItem("city")) $(".address ul").empty(); list.forEach(function(value,index,arr){ $(".address ul").append( `
  • 城市名
    ${value}
  • `) }); $.popup('.popup-city'); $(".address ul li").on("click",function() { self.get($(this).find(".item-after").text(),function(res){ self.RenderingPage(res) $.closeModal('.popup-city') }) }) }) }, get: function (params,callback) { $.showIndicator() $.ajax({ url: this.BaseUrl.index, type: "GET", data: { cityname: params }, success: function (res) { callback(res.result) }, error: function (err) { $.toast("获取天气信息失败,请联系管理员"); } }) } } bom._weather = Weather })(window,document)