How do I dynamically populate html elements with JSON Data with Javascript not jQuery?

后端 未结 7 1694
无人及你
无人及你 2020-12-24 09:46

I have this following JSON data snippit:

{\"items\": [
 {
   \"title\": \"sample 1\",
   \"author\": \"author 1\"
 },
 {
  \"title\": \"sample 2\",
  \"aut         


        
相关标签:
7条回答
  • 2020-12-24 10:25

    Better late than never... I recently made a lib to do just this!

    FragBuilder is the library.. usage is pretty simple: for the example you have posted you would need to change around the JSON a bit to make it a bit more semantic...

    var frag = [{"items": [
     {
       "title": "sample 1",
       "author": "author 1"
     },
     {
      "title": "sample 2",
      "author": "author 2"
     }
    ]}];
    

    would become

    var frag = [ { "childNodes" : [ { "childNodes" : [ { "textContent" : "sample 1" } ],
              "tagName" : "H5"
            },
            { "childNodes" : [ { "textContent" : "By: author 1" } ],
              "tagName" : "P"
            },
            { "childNodes" : [ { "textContent" : "sample 2" } ],
              "tagName" : "H5"
            },
            { "childNodes" : [ { "textContent" : "By: author 2" } ],
              "tagName" : "P"
            }
          ],
        "className" : "news-story",
        "tagName" : "DIV"
      } ];
    

    then you would generate a DocumentFragment by calling FragBuilder(frag)

    There is also a reverse function if you find it easier to template using HTML then convert to JSON https://gist.github.com/2313580 (note, whitespace between tags is not handled and will cause failures)

    0 讨论(0)
提交回复
热议问题