简体   繁体   中英

Parse Json value to html tag

How can i parse each tag of k and v to html tag.

var json = $.parseJSON(data);
var x = 0;
$(json).each(function(i, val) {
    $.each(val, function(k, v) {

        var my_href = "#";
        var img_source = "..img";
        var my_title = "...abcd";
        var slider_index = "wows_" + x;

        x++; //increment link id

        $('#ws_images').html('<li><a href="' + my_href + '"><img src="' + img_source + '" alt="" title="' + my_title + '" id="' + slider_index + '" /></a></li>');

    });
});

The json is as follows:

[  
   {  
      "news_id":"8",
      "title":"ddd",
      "description":"ddd",
      "photo":"News_images\/20020_1116863714996046_8844424307040103167_n.jpg",
      "posted_on":"2015-07-12 12:54:48",
      "news_type":"image_slider",
      "dept_id":"1"
   }
]

The value of k return the tag name but how can each tag element be parsed into the html tag.

<li><a href="' + my_href + '"><img src="' + img_source + '" alt="" title="' + my_title + '" id="' + slider_index + '" /></a></li>

Try utilizing single $.each() , substituting .append() for html()

 var data = [{ "news_id": "8", "title": "ddd", "description": "ddd", "photo": "News_images\\/20020_1116863714996046_8844424307040103167_n.jpg", "posted_on": "2015-07-12 12:54:48", "news_type": "image_slider", "dept_id": "1" }]; $.each(data, function(k, v) { $("#ws_images") .append("<li><a href=#>" + "<img src=" + v. photo + " alt=''" + " title=" + v.title + " id=wows_" + k + " />" + "</a></li>"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <ul id="ws_images"></ul> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM