使用jquery基于json数据更改图像

时间:2016-07-11 18:20:52

标签: javascript jquery json

我正在摆弄jquery和json,基本上是想制作天气应用程序。我想根据数据显示GIF。

来自API的示例数据:

"time": 1468261711,
"summary": "Clear",
"icon": "clear-day",

我已经知道了可能的值,所以我想创建一个数组,如果摘要对象是" Clear",显示sunny.gif。

实现这一目标的常用方法是什么?

2 个答案:

答案 0 :(得分:1)

Without more example code, it's hard to advise on the best solution.

You can create an object with keys that reference the summary and values that point to the GIF.

ie:

var gifs = {
    "Clear": "clear.gif",
    "Sunny": "sunny.gif"
};

Now when you parse through the data from the API. You can get the relevant GIF.

var weatherObject = {
    "time": 1468261711,
    "summary": "Clear",
    "icon": "clear-day"
}

var gif = gifs[weatherObject.summary]; // Returns clear.gif

Read more about JS Objects here.

答案 1 :(得分:0)

You can have a hash object that maps the weather summary to the gif like:

var map = {
    "Cloudy": {
        "media": "../images/weather-cloudy.gif"
    },
    "Clear": {
        "media": "../images/weather-sunny.gif"
    }
};

On your API ajax callback you could render based on this map info:

$.get("api/weather?q=Newyork")
    .done(function (data) {

        var html = yourHandlebarsCompiledTemplateForExample({
           apiData: data,
           mappedInfo: map[data.summary]
        });

        $(html).appendTo("#weather-contanier");
    });