将JSON值附加到figcaption

时间:2015-02-28 17:21:17

标签: javascript jquery json

我有一个带有以下结构的JSON文件,我希望在每个图像下显示品牌,型号,名称和价格,但我显然想要不同的值。

[
    {"instrumentGroup":"Woodwind", "category1":"Instrument", "name":" Bb Clarinet", "price":"£400","quantityAvailable":"10", "description":"ABS resin Buffet B12 student clarinet, clear sound.", "rating":"4", "make":"Buffet", "model":"B12"},
    {"instrumentGroup":"Woodwind", "category1":"Instrument", "name":"Bb Clarinet", "price":"£1700","quantityAvailable":"10", "description":" CX with full round sound and clear tone.", "rating":"5", "make":"Yamaha", "model":"YCL-CX"},
    {"instrumentGroup":"Woodwind", "category1":"Instrument", "name":"Bass Clarinet", "price":"£3500","quantityAvailable":"5", "description":"Student Grenadilla wood bass clarinet with silver plated keywork. Range down to Eb.", "rating":"4", "make":"Buffet", "model":"BC1180"}
]

该文件比这个大得多,但现在只需要处理一点。

在我的html中,我有多个容器,因为页面上的内容比此更多,但产品信息的结构如下所示。

<article id="prodList">
            <article id="products">
                <section id="row">
                    <figure class="prodInfo">
                        <!--this makes the whole product area clickable!--><a href="#link">
                            <span class="link"></span>
                        </a>
                        <img src="Images/saxophone.png" alt="instrument" width="100" height="100">

                            <figcaption>

                            </figcaption>
                    </figure>

                    <figure class="prodInfo">
                        <!--this makes the whole product area clickable!--><a href="#link">
                            <span class="link"></span>
                        </a>
                        <img src="Images/saxophone.png" alt="instrument" width="100" height="100">

                            <figcaption>

                            </figcaption>
                    </figure>

                </section>  
            </article>  
</article>

我想在figcaption中显示信息,make / model在一行,名字在下一个然后价格在下一个。下面我的.js文件打印出每个图像下JSON文件中的最后一个值,但我无法确定如何打印每个值,然后在达到第18个值时停止。

$.getJSON("products.json", function(result){

        $.each(result, function(key, val){
            $('figcaption').html(val.make + " " + val.model + "<br/>" + val.name + "<br/>" + val.price);
        });
    });

任何帮助将不胜感激。最终我将使用一个分页器在下一页显示接下来的18个值,但是一旦第一个工作,我相信这应该更容易。 主要问题是如何将它们分开,以便在每个div中打印一个。

感谢。

1 个答案:

答案 0 :(得分:1)

尝试

$.getJSON("products.json", function(result) {
    $.each(result, function(key, val){
        if (key < 18) {
            $("figcaption").eq(key).html(val.make + " " 
            + val.model + "<br/>" + val.name + "<br/>" + val.price);
        }
    });        
});

jsfiddle http://jsfiddle.net/guest271314/6ftjLLjv/