如何基于JSON创建页面部分

时间:2011-04-11 14:30:01

标签: javascript jquery html json

我有jQuery滑块代码,我想通过JSON url填充。下面是我开始使用的示例JSON:

{
  "Context": null,
  "IsGeneric": false,
  "Items": [
    {
      "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla tincidunt condimentum lacus. Pellentesque ut diam....<a href="#" >read more</a>",
      "MediaUrl": "\/images\/image1.jpg",
      "AlternativeText": "15+ Excellent High Speed Photographs",
      "Height": 1050,
      "ThumbnailUrl": "\/images\/image1-thb.jpg",
      "Width": 1680
    },
    {
      "Description": "Vestibulum leo quam, accumsan nec porttitor a, euismod ac tortor. Sed ipsum lorem, sagittis non egestas id, suscipit....<a href="#" >read more</a>",
      "MediaUrl": "\/images\/image2.jpg",
      "AlternativeText": "20 Beautiful Long Exposure Photographs",
      "Height": 1050,
      "ThumbnailUrl": "\/images\/image2-thb.jpg",
      "Width": 1680
    },
    {
      "Description": "Liquam erat volutpat. Proin id volutpat nisi. Nulla facilisi. Curabitur facilisis sollicitudin ornare....<a href="#" >read more</a>",
      "MediaUrl": "\/images\/image3.jpg",
      "AlternativeText": "35 Amazing Logo Designs",
      "Height": 1050,
      "ThumbnailUrl": "\/images\/image3-thb.jpg",
      "Width": 1680
    },
    {
      "Description": "Quisque sed orci ut lacus viverra interdum ornare sed est. Donec porta, erat eu pretium luctus, leo augue sodales....<a href="#" >read more</a>",
      "MediaUrl": "\/images\/image4.jpg",
      "AlternativeText": "Create a Vintage Photograph in Photoshop",
      "Height": 1050,
      "ThumbnailUrl": "\/images\/image4-thb.jpg",
      "Width": 1680
    }
  ]
}

如何将其转换为此?:

    <div id="featured" >
      <ul class="ui-tabs-nav">
        <li class="ui-tabs-nav-item ui-tabs-selected" id="nav-fragment-1"><a href="#fragment-1"><img src="images/image1-small.jpg" alt="" /><span>15+ Excellent High Speed Photographs</span></a></li>
        <li class="ui-tabs-nav-item" id="nav-fragment-2"><a href="#fragment-2"><img src="images/image2-small.jpg" alt="" /><span>20 Beautiful Long Exposure Photographs</span></a></li>
        <li class="ui-tabs-nav-item" id="nav-fragment-3"><a href="#fragment-3"><img src="images/image3-small.jpg" alt="" /><span>35 Amazing Logo Designs</span></a></li>
        <li class="ui-tabs-nav-item" id="nav-fragment-4"><a href="#fragment-4"><img src="images/image4-small.jpg" alt="" /><span>Create a Vintage Photograph in Photoshop</span></a></li>
      </ul>

    <!-- First Content -->
    <div id="fragment-1" class="ui-tabs-panel" style="">
        <img src="images/image1.jpg" alt="" />
         <div class="info" >
            <h2><a href="#" >15+ Excellent High Speed Photographs</a></h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla tincidunt condimentum lacus. Pellentesque ut diam....<a href="#" >read more</a></p>
         </div>
    </div>

    <!-- Second Content -->
    <div id="fragment-2" class="ui-tabs-panel ui-tabs-hide" style="">
        <img src="images/image2.jpg" alt="" />
         <div class="info" >
            <h2><a href="#" >20 Beautiful Long Exposure Photographs</a></h2>
            <p>Vestibulum leo quam, accumsan nec porttitor a, euismod ac tortor. Sed ipsum lorem, sagittis non egestas id, suscipit....<a href="#" >read more</a></p>
         </div>
    </div>

    <!-- Third Content -->
    <div id="fragment-3" class="ui-tabs-panel ui-tabs-hide" style="">
        <img src="images/image3.jpg" alt="" />
         <div class="info" >
            <h2><a href="#" >35 Amazing Logo Designs</a></h2>
            <p>liquam erat volutpat. Proin id volutpat nisi. Nulla facilisi. Curabitur facilisis sollicitudin ornare....<a href="#" >read more</a></p>
         </div>
    </div>

    <!-- Fourth Content -->
    <div id="fragment-4" class="ui-tabs-panel ui-tabs-hide" style="">
        <img src="images/image4.jpg" alt="" />
         <div class="info" >
            <h2><a href="#" >Create a Vintage Photograph in Photoshop</a></h2>
            <p>Quisque sed orci ut lacus viverra interdum ornare sed est. Donec porta, erat eu pretium luctus, leo augue sodales....<a href="#" >read more</a></p>
         </div>
    </div>

</div>

10 个答案:

答案 0 :(得分:1)

结帐jqote2,它取决于jQuery或下划线的_template方法。

http://aefxx.com/jquery-plugins/jqote2/
http://documentcloud.github.com/underscore/

你的json示例需要使用\“

进行href转义

使用下划线的示例

var x = _.template("hello world a is <%= a %>, <% for (var i=0; i < 4; i++) { %> <%= i %>     <% } %>", {a: 77});

x; //#=&gt;你好世界a是77,0 1 2 3

答案 1 :(得分:0)

从内存中的虚拟元素开始。如果你在内存中构建HTML并将其一次性插入DOM中,而不是重复的DOM写入,那么整个过程将快100倍。

var myOutput = document.createElement('div')

然后循环浏览数据并将内容附加到“myOutput”中,直到完成为止。

$(myOutput).append(....)

请参阅:http://api.jquery.com/append/

然后将其添加到页面中:

$('body').append(myOutput)

答案 2 :(得分:0)

您应该查看this question及其答案。

如果它不适合您,请尝试使用Google搜索“Javascript模板”。

答案 3 :(得分:0)

您可能希望查看客户端模板机制,例如jQuery.tmplEmbedded JavaScript。 EJS中示例的标签部分如下所示:

<% $.each(Items, function(index, item) { %>
    <div id="fragment-1" class="ui-tabs-panel" style="">
        <img src="<%= item.MediaUrl %>" alt="" />
         <div class="info" >
            <h2><a href="#" ><%= item.AlternativeText %></a></h2>
            <p><%= item.Description %></p>
         </div>
    </div>
<% } %>

答案 4 :(得分:0)

普通JS:

<script>
var res = {
  "Context": null,
  "IsGeneric": false,
  "Items": [
    {
      "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla tincidunt condimentum lacus. Pellentesque ut diam....<a href="#" >read more</a>",
      "MediaUrl": "\/images\/image1.jpg",
      "AlternativeText": "15+ Excellent High Speed Photographs",
      "Height": 1050,
      "ThumbnailUrl": "\/images\/image1-thb.jpg",
      "Width": 1680
    },
.
.
.
  ]
}
window.onload=function() {
  var container = document.getElementById("featured");
  for (var i=0, n=res.Items.length;i<n;i++) {
    var item = res.Items[i]
    var div = document.createElement("div");
    div.id = "fragment-"+(i+1);
    div.className="ui-tabs-panel"; 
    div.style="";
    var img = document.createElement("img");
    img.src=item.MediaUrl;
    img.alt=item.AlternativeText
    var innerDiv = document.createElement("div");
    innerDiv.className="info";
    var header = document.createElement("h2");
    var link = document.createElement("a");
    link.href="#";
    link.innerHTML=item.description;
    header.appendChild(link);
    innerDiv.appendChild(header);
    div.appendChild(img);
    div.appendChild(innerDiv);
    container.appendChild(div);
  }
}  
</script>
<div id="featured" >
      <ul class="ui-tabs-nav">
        <li class="ui-tabs-nav-item ui-tabs-selected" id="nav-fragment-1"><a href="#fragment-1"><img src="images/image1-small.jpg" alt="" /><span>15+ Excellent High Speed Photographs</span></a></li>
        <li class="ui-tabs-nav-item" id="nav-fragment-2"><a href="#fragment-2"><img src="images/image2-small.jpg" alt="" /><span>20 Beautiful Long Exposure Photographs</span></a></li>
        <li class="ui-tabs-nav-item" id="nav-fragment-3"><a href="#fragment-3"><img src="images/image3-small.jpg" alt="" /><span>35 Amazing Logo Designs</span></a></li>
        <li class="ui-tabs-nav-item" id="nav-fragment-4"><a href="#fragment-4"><img src="images/image4-small.jpg" alt="" /><span>Create a Vintage Photograph in Photoshop</span></a></li>
      </ul>
</div>

答案 5 :(得分:0)

我为divs部分拍了一枪。我把它写在我的头顶,所以它可能包含错别字等,但可以给你一个想法

for (var i=0; i< jsonDesc.length; i++) {
  $("<div>").attr("id", "fragment-"+(i+1))
      .addClass("ui-tabs-panel")
      .append$("<img>").attr("src", jsonDesc[i].Items.MediaUrl)
      .append(
          $("<div>").addClass("info").append(
              $("<h2>")
                  .append("<a>").attr("href", "#").html(jsonDesc[i].Items.AlternativeText)
            )
        );
  if (i>0) {
    $("#fragment-"+(i+1)).addClass ("ui-tabs-hide");
}

答案 6 :(得分:0)

使用DOMBuilder,您可以执行以下操作:

http://jsfiddle.net/insin/kJVBS/1/

DIV({id: "featured"},
  UL({"class": "ui-tabs-nav"},
    LI.map({"class": "ui-tabs-nav-item"}, items, function(item, attrs, idx) {
      attrs["id"] = "nav-fragment-" + (idx + 1);
      if (idx === 0) {
        attrs["class"] += " ui-tabs-selected";
      }
      return A({href: "#fragment-" + (idx + 1)},
        IMG({src: item.ThumbnailUrl, alt: ""}),
        SPAN(item.AlternativeText)
      );
    })
  ),
  DOMBuilder.fragment.map(items, function(item, idx) {
    return DIV({id: "fragment-" + (idx + 1), "class": "ui-tabs-panel"},
      IMG({src: item.MediaUrl, alt: ""}),
      DIV({"class": "info"},
        H2(A({"href": "#"}, item.AlternativeText)),
        P({innerHTML: item.Description})
      )
    );
  })
)

如果DOM方法开始明显变慢,您还可以使用这个完全相同的代码来构建相应的HTML以便innerHTML插入(包括您定义的任何事件处理程序的注册)。

答案 7 :(得分:0)

我会使用微软新的(仍处于测试阶段)jQuery tmpl插件。它比自己手动构建DOM元素简洁得多。

您的问题的完整实施示例就在这里。

http://jsbin.com/afoko5/latest

这会生成你想要的html,但由于缺少图像和css类,它看起来不太好。

希望这有帮助。

答案 8 :(得分:0)

jQuery Templates非常适合这种事情。

答案 9 :(得分:0)

看看我用你的样本数据创建的这个小提琴: http://jsfiddle.net/subhamsaha1004/ct3sw/

它包含一个基本的模板功能,可以更轻松地创建html。它使用纯JavaScript。代码保持非常简单,因为目的只是创建一个可以进一步构建的演示。

解析器代码如下所示:

var Parser = {
    template: '<div class="slide"><img src="{{imgsrc}}" alt="" /><div class="info" ><h2><a href="#" >{{title}}</a></h2><p>{{description}}</p></div></div>',
    compile: function(template, data) {
        template = template.replace(/\{\{imgsrc\}\}/g, data.MediaUrl).replace(/\{\{title\}\}/g, data.AlternativeText).replace(/\{\{description\}\}/g, data.Description);

        return template;
    },
    parse: function(response) {
        var tpl = '', i = 0, len = 0, html = '';
        for(i = 0, len = response.length; i < len; i++) {
            tpl = this.template;
            html += this.compile(tpl, response[i]);
        }

        return html;
    }
};

检查整个代码的小提琴。