How to structure JSON and build HTML via jQuery

后端 未结 4 1484
臣服心动
臣服心动 2021-02-03 14:14

Beginner here trying to figure out best way to structure some JSON and output the below nested

    Each of the bolded items below are the values in the JSON. How

4条回答
  •  广开言路
    2021-02-03 15:13

    First recommendation is taking a look at the JSON site. It has some examples of JSON code in JavaScript.

    If you're structuring the whole thing out of JSON, I'd do it like this.

    var topics = {
      topic1: {
        title : "Topic 1",
        items : [
          {title: "1a", link: "http://www.example.com/", text: "Link Text or HTML"},
          {title: "1b", link: "http://www.example.com/", text: "Link Text or HTML"}
        ]
      },
      topic2: {
        title : "Topic 2",
        items : [
          {title: "2a", link: "http://www.example.com/", text: "Link Text or HTML"},
          {title: "2b", link: "http://www.example.com/", text: "Link Text or HTML"}
        ]
      }
    };
    

    If you only need a subset of the information you could do it differently, but this should give you something to start with.

    To update the DOM with these values, you can loop through the appropriate array from the JSON object and then populate the values. Use the jQuery .html( htmlString ) function.

    I hope this helps you get started.

提交回复
热议问题