如何基于 JSON 创建页面部分

发布于 2024-11-01 01:28:18 字数 4811 浏览 0 评论 0原文

我有 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>

I have jQuery slider code that I want to populate via a JSON url. Below is a sample JSON I am starting with:

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

How do I transform it to this?:

    <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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

阿楠 2024-11-08 01:28:18

查看 jqote2,它依赖于 jQuery 或 underscore 的 _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 的示例; //# => hello world a is 77, 0 1 2 3

Checkout jqote2 which depends on jQuery or underscore's _template method.

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

your json example needs to have href escaped with \"

example using underscore

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

x ; //# => hello world a is 77, 0 1 2 3

攒眉千度 2024-11-08 01:28:18

我尝试了一下 div 部分。我把它写在我的头上,所以它可能包含错别字等,但可以给你一个想法

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");
}

I gave it a shot for the divs part. I wrote it on top of my head so it may contain typos etc., but can give you an idea

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");
}
羁〃客ぐ 2024-11-08 01:28:18

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

var myOutput = document.createElement('div')

然后循环遍历数据并将内容附加到“myOutput”中,直到完成。

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

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

然后将其附加到页面中:

$('body').append(myOutput)

Start with a dummy element in memory. This whole thing will be 100x faster if you build the HTML in memory and insert it into the DOM all in one go, rather than repeated DOM writes.

var myOutput = document.createElement('div')

Then you loop through your data and append content into "myOutput" until you're done.

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

See: http://api.jquery.com/append/

Then append it into the page:

$('body').append(myOutput)
冷弦 2024-11-08 01:28:18

您应该查看此问题及其答案。

如果它不适合您,请尝试在谷歌上搜索“Javascript 模板”。

You should check out this question and its answers.

If it doesn’t work for you, try googling for "Javascript templates".

奢欲 2024-11-08 01:28:18

您可能想查看客户端模板机制,例如 jQuery.tmpl嵌入式 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>
<% } %>

You might want to look at a client side templating mechanism e.g. jQuery.tmpl or Embedded JavaScript. The tab part of your example in EJS would look like this:

<% $.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>
<% } %>
假面具 2024-11-08 01:28:18

普通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>

Plain 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>
流云如水 2024-11-08 01:28:18

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

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

http://jsbin.com/afoko5/latest

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

希望这有帮助。

I would use the new (still in beta) jQuery tmpl plugin from Microsoft. It's much more concise than manually building the DOM elements yourself.

A full implementation example for your question is here.

http://jsbin.com/afoko5/latest

This generates the html you want, but it doesn't look very good because of the missing images and css classes.

Hope this helps.

黯淡〆 2024-11-08 01:28:18

使用 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})
      )
    );
  })
)

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

With DOMBuilder, you could do something like this:

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

You'll also be able to use this exact same code to build the corresponding HTML for insertion with innerHTML (including registration of any event handlers you define) if the DOM approach starts to become noticeably slow.

咋地 2024-11-08 01:28:18

jQuery 模板 非常适合这种事情。

jQuery Templates is perfect for this kind of thing.

旧故 2024-11-08 01:28:18

看看我用您的示例数据创建的这个小提琴:
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;
    }
};

检查整个代码的小提琴。

Check out this fiddle I created with your sample data:
http://jsfiddle.net/subhamsaha1004/ct3sw/

It has a basic templating feature included that makes it easier to create the html. It uses pure javascript. The code has been kept very simple as the purpose was only to create a demo which you can further build upon.

The parser code looks something like this:

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;
    }
};

Check the fiddle for the entire code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文