简体   繁体   English

JSON,转换为HTML以与Isotope.js一起使用

[英]JSON, converting to HTML to use with Isotope.js

UPDATE: I have changed this question around. 更新:我已经改变了这个问题。 I was unable to figure it out, even though I'm sure I got two great answers. 即使我确定有两个很好的答案,我也无法弄清楚。 I have tried to simplify this question so I can figure it out in a more methodical manner. 我试图简化这个问题,以便我可以更系统地解决。 I hope this can help other newbs like myself... 我希望这可以帮助像我这样的其他新手...

I would like to use isotope.js to display selected data from a JSON (this question is related to the question I posted here): 我想使用isotope.js来显示JSON中的选定数据(此问题与我在此处发布的问题有关):

Best way to create grid from JSON data which dynamically resizes based on number of entries 从JSON数据创建网格的最佳方法,该方法会根据条目数动态调整大小

I've been reading about isotope today (I'm also a newbie to Javascript), and I'm sure this question will seem elementary to a lot of you. 我今天一直在阅读有关同位素的信息(我也是Javascript的新手),并且我敢肯定,这个问题对于您中的许多人来说似乎都是基础知识。 Anyways here goes... 无论如何这里...

From what I see, I need to have the html in this format to feed to isotope (this is taken from the basic example on isotope found here - https://github.com/DaweiCheng/isotope-tutorial/blob/master/basic.html ): 从我看来,我需要使用这种格式的html来馈送给同位素(这取自此处找到的有关同位素的基本示例-https: //github.com/DaweiCheng/isotope-tutorial/blob/master/basic .html ):

<div class="element other nonmetal   " data-symbol="H" data-category="other">
      <p class="number">1</p>
      <h3 class="symbol">H</h3>
      <h2 class="name">Hydrogen</h2>
      <p class="weight">1.00794</p>
    </div>

So, if I had a JSON like so (please assume multiple records that are similar): 因此,如果我有这样的JSON(请假设多个相似的记录):

[{"name":"Hydrogen","number":1,"symbol":"H","weight":1.00794},{"name":"Helium","number":2,"symbol":"He","weight":4.002602},{"name":"Lithium","number":3,"symbol":"Li","weight":6.941},{"name":"Beryllium","number":4,"symbol":"Be","weight":9.012182},{"name":"Boron","number":5,"symbol":"B","weight":10.811},...]

*Please note that any fields that are numbers in the JSON are integers, not strings. *请注意,JSON中任何数字字段都是整数,而不是字符串。

I want to turn the JSON into this: 我想将JSON转换为:

<div id="container">

<div class="element">
<p class="number">1</p>
<h3 class="symbol">H</h3>
<h2 class="name">Hydrogen</h2>
<p class="weight">1.00794</p>
</div>
<div class="element">
...
</div>

</div>

How would I convert the JSON into the required HTML? 如何将JSON转换为所需的HTML?

To make things simple (for me), I want the div class for each record to always be element (so as I learn to change isotope, I can initially begin by using the css from their tutorials). 为了简单起见(对我而言),我希望每个记录的div类始终是元素(因此,当我学习改变同位素时,我首先可以从其教程中使用css开始)。 The container div doesn't need to be repeated for each record, all the records will be displayed within the container (I guess that doesn't need saying)... 容器div不需要为每个记录重复,所有记录都将显示在容器内(我想不需要说)...

I have tried doing it using the answers below (which answer how I previously asked this question), however when doing so I either got nothing returned (and no errors in the console), or I got what appears like an empty table cell. 我尝试使用下面的答案(该答案回答了我之前提出的问题)来进行操作,但是这样做时,我什么也没有返回(控制台中没有错误),或者出现了一个空表单元格。

Any help is greatly appreciated. 任何帮助是极大的赞赏。 I'm very sorry to the two users who responded, I'm thankful for your help and I'll continue to play with your answers in the hope I figure it out. 非常感谢两位回复的用户,感谢您的帮助,我将继续研究您的答案,希望我能解决。

Create a function whose role is to accept the result from your Ajax and it iterates over every object, grabs the requisite data from it and outputs a div with the needed information. 创建一个函数,该函数的作用是接受Ajax的结果,并迭代每个对象,从中获取必需的数据,并输出包含所需信息的div。

For example: 例如:

function renderUser(ajaxResponse) {

    // turn string response to JSON array
    var responseArray = JSON.parse(ajaxResponse);

    // make sure there is a response
    if (responseArray.length > 0) {

        // get container
        var container = document.getElementById("container");

        // iterate over each response
        for (var i = 0; i < responseArray.length; i += 1) {

            // create the elems needed
            var player = document.createElement("div");
            player.className = "players";
            player.data-Name = responseArray[i].name;

            var score = document.createElement("p");
            score.className = "score";
            score.innerHTML = responseArray[i].score;

            var name = document.createElement("h3");
            name.className = "name";
            name.innerHTML = responseArray[i].name;

            var city= document.createElement("p");
            city.className = "city";
            city.innerHTML = responseArray[i].city;

            // append them all to player wrapper
            player.appendChild(score);
            player.appendChild(name);
            player.appendChild(city);

            // append player to container
            container.appendChild(player);
        }
    } 
}

edit: 编辑:

Took the liberty of making a fiddle to do exactly what you wanted here: http://jsfiddle.net/92FgL/ 随意摆弄小提琴来完全按照您的意愿在这里进行操作: http : //jsfiddle.net/92FgL/

If you wanted to use more jQuery and less vanilla js you could do something like: 如果您想使用更多的jQuery和更少的香草js,则可以执行以下操作:

// document.ready shorhand
$(function() {
  var $container;

  // store destination element
  $container = $('#container');

  $.getJSON('myjson.json', function(data) {
    var items;

    // initialize array where we'll store html
    items = [];

    // loop through ajax response
    $.each(data, function() {
      var html;

      // build player html
      html = "<div class=\"players\" data-name=\"" + data.name + "\"> \
      <p class=\"score\">" + data.score + "</p> \
      <h3 class=\"name\">" + data.name + "</h3> \
      <p class=\"city\">" + data.city + "</p> \
      </div>"

      // add new html onto array
      items.push(html);
    });

    // squish all the html into a string
    items.join('');

    // set the html of the container to the html built above
    $container.html(items);
  });

  $container.isotope({
    itemSelector: '.players'
  });
});

You could use jQuery tmpl plugin. 您可以使用jQuery tmpl插件。 It's not developed anymore, but it works really well. 它不再开发了,但是效果很好。

https://github.com/jquery/jquery-tmpl https://github.com/jquery/jquery-tmpl

Template defined in html HTML中定义的模板

    <script id="myTmpl" type="x-jquery-tmpl">
        <div class="player" data-name="${name}">
            <p class="score">${score}</p>
            <h3 class="name">${name}</h3>
            <p class="city">${city}</p>
        </div>
    </script>

Data pushed to the tmpl with jquery. 数据通过jquery推送到tmpl。 Note: you don't need to cycle through data with a $.each or for: you can push the whole array and the tmpl plugin will handle it, pushing the data to the template for each entry of the array. 注意:您不需要使用$ .each或for遍历数据:您可以推送整个数组,而tmpl插件将处理该数组,并将数据推送到该数组每个条目的模板。

    $.getJSON('myjson.json', function(data) {
         var items = $('#mytmpl').tmpl(data);
         //items is your html object containing a div for each element of data.
         //you can push it to the dom through jQuery 
         //or $container.isotope( 'insert', items );
    });

Hope it helps. 希望能帮助到你。

Please ask further if it's not clear. 请进一步询问是否不清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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