2015-07-12 86 views
0

如何解析k和v的每個標記到html標記。解析JSON值到html標記

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>'); 

    }); 
}); 

將JSON如下:

[ 
    { 
     "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" 
    } 
] 

k的值返回標籤名稱,但如何在每個標籤元件被解析成HTML標記。

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

回答

0

嘗試利用單個$.each(),用於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>

.append()