【问题标题】:JavaScript loop printing a HTML codeJavaScript 循环打印 HTML 代码
【发布时间】:2016-02-09 14:21:02
【问题描述】:

我有这个 HTML 代码:

<div class="content">   

<article class="underline">
        <a href="incidente.html"><img id="incidente"  
         src="img/buraco.jpg" alt="Incidente" /></a>
        <h2><a href="basic_markup.html" id="tit"></a></h2>
        <p id="desc">Esse buraco na rua Montes Claros já está há 1 ano 
         trazendo transtornos aos moradores</p><p></p>
        <div class="date" id="date"></div>
        <img class="tick" alt="não resolvido" src="img/no-tick.png">
        <img class="apoio" alt="apoiar" src="img/apoio.png">

</article>

还有这个接收数组的ajax:

$.ajax({

  type: "GET",
  url: "http://localhost/again/www/index.php",
  dataType: "json",

    success: function (data) {

        var tit = "";
        // Loop over each object
        for (var $i = 0; $i < data.length; $i++) {
            var object = data[$i];

            tit+=  object.titulo;


        }
              $('#tit').html(tit);
     }
    });

</script>

现在,它在相同的 HTML 代码中插入所有内容(当然,因为我没有 foreach),但我想为我收到的每一行(每个“tit”)显示这个 HTML。 ..有人能帮我吗?

【问题讨论】:

  • 您想为每个结果生成一个新的文章块吗?
  • @Dontfeedthecode 是的,正是我想要的。为每个结果生成一篇新文章...
  • 您能否粘贴一个在您的 $.ajax 函数中返回的 JSON 示例?
  • @Dontfeedthecode 我的 ajax 正在接收这样的 Json 数组:[{"codigo":"32","0":"32","titulo":"Some title here","1 ":"这里有一些标题","descricao":"这是我的描述","2":"这是我的描述","data":"2015-10-29 21:48:13","3" :"2015-10-29 21:48:13"l},{"codigo":"33","0":"33","titulo":这里的标题,"1":这里的标题,"descricao" :description here,"2":description here,"data":"2015-10-30 20:45:46","3":"2015-10-30 20:45:46"}]
  • @Dontfeedthecode 对于每个标题我想生成一篇文章...

标签: javascript html ajax loops foreach


【解决方案1】:

如果我理解您的意思,您有多篇文章并且您想动态更改它们的标题?

如果是这样,首先你应该删除;

$('#tit').html(tit);

然后在循环里面放这个:

$('#content article:eq('+$i+')').find('#tit').html(object.titulo);

仅当$i 与其父元素的索引相同时才有效。

【讨论】:

    【解决方案2】:

    我的理解是:你有一个数组,里面有你想要循环显示的文本。

    如果这是你的数组:

    ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5"]
    

    那么你希望它显示出来

    <element>Text 1</element>
    <element>Text 2</element>
    <element>Text 3</element>
    <element>Text 4</element>
    <element>Text 5</element>
    

    代码中的问题

    我在您的代码中看到的问题是您使用的是 jquery 的 .html(arrayItem),它将覆盖元素内的任何现有文本。

    看看我的解决方案:(http://jsfiddle.net/ProgrammerKid/v6upsLp8/)

    HTML

    <div id="tit"></div>
    

    JavaScript

    $(document).ready(function () {
        var tit = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5"];
    
        for (var i in tit) {
            var element = document.createElement("h2");
            element.innerHTML = tit[i];
            $("#tit").append(element);
        }
    });
    

    这里我们使用 jQuery 的.append,我们创建了一个node,并将node 附加到包装元素中。

    如果您有任何问题,请在下方留言,我会尽快回复

    【讨论】:

    • 谢谢,但不,它只是打印标题,我想为每个标题打印(

      ) 图片(),描述(即 ->

      Esse buraco na rua Montes Claros já está há 1 ano trazendo transtornos aos moradores

      ),日期(
      20 mar 2012
      )和另外两张小图片(在“img/no-tick.png 和”img/apoio.png"> 中)。明白吗?
    • 相同的概念......只需将 for 循环相乘以满足每个给定条件
    • 但是,我怎样才能循环处理不是来自我的数据库的东西,我的 html 中的东西,比如 我想为每个标题(标题)重复吗?
    • document.getElementsByClassName("elementsClassName")... 这将返回一个包含所有元素的array。 =)
    【解决方案3】:

    您可以创建一个返回带有 html 标记的字符串的函数。如果您需要填充 html 模板,那么您需要将参数发送到该函数。以下是 javascript 的示例:

    http://jsfiddle.net/fnLjcfvr/1/

    function getHtml(title){
        var html = "";
        html += '<div class="content">';
        html += '';
        html += '<article class="underline">';
        html += '<a href="incidente.html"><img id="incidente"';  
        html += 'src="img/buraco.jpg" alt="Incidente" /></a>';
        html += '<h2><a href="basic_markup.html" id="tit"> + ' title ' + </a></h2>';
        html += '<p id="desc">Esse buraco na rua Montes Claros já está há 1 ano          trazendo transtornos aos moradores</p><p></p>';
        html += '<div class="date" id="date"></div>';
        html += '<img class="tick" alt="não resolvido" src="img/no-tick.png">';
        html += '<img class="apoio" alt="apoiar" src="img/apoio.png">';
        html += '';
        html += '</article>';
    
        return html;
    }
    

    【讨论】:

      【解决方案4】:

      让事情井井有条的最佳选择是使用像把手这样的模板引擎。我已经为您设置了一个 jsfiddle,它使用您提供的示例数据呈现您的文章(需要进行一些格式化才能正常工作)。

      http://jsfiddle.net/4ud6rLfq/10/

      // This is what you'll need to get the data via AJAX
      var source   = $("#template").html();
      var template = Handlebars.compile(source);
      $.ajax({
          type: "GET",
          url: "http://localhost/again/www/index.php",
          dataType: "json",
          success: function (data) {
              $.each(data, function(key, value) {
                  $('#articles').append(template(value));
              });
          }
      });
      
      // A demo using the data you provided (formatted a bit)
      var data = [
          {
              "codigo":"32",
              "titulo":"Some title here",
              "descricao":"Here is my description",
              "data":"2015-10-29 21:48:13"
          },{
              "codigo":"33",
              "titulo":"Title here",
              "descricao":"description here",
              "data":"2015-10-30 20:45:46"
          }
      ];
      
      var source   = $("#template").html();
      var template = Handlebars.compile(source);
      
      $.each(data, function(key, value) {
          $('#articles').append(template(value));
      });
      

      还有您需要的 HTML:

      <script id="template" type="text/x-handlebars-template">
          <article class="underline">
              <a href="#">
                   <img class="incidente" src="" alt="{{titulo}}" />
              </a>
              <h2><a href="#">{{titulo}}</a></h2>
              <p class="desc">{{descricao}}</p>
              <p></p>
              <div class="date" class="date">{{data}}</div>
              <img class="tick" alt="não resolvido" src="img/no-tick.png">
              <img class="apoio" alt="apoiar" src="img/apoio.png">
          </article>
      </script>
      
      <div id="articles"></div>
      

      有一个使用您的 $.ajax 函数的示例被注释掉了,下面的另一个示例使用了 data 变量——您需要做的就是在 jQuery 之后在您的页面中包含把手,这应该很好。您可以编辑模板中的变量以匹配您通过 ajax 传回脚本的任何内容。

      基本上发生的事情是首先为数据设置模板,然后循环遍历数据并将每个项目绑定到模板,然后将项目模板作为 HTML 附加到 #articles 容器,然后移至下一项,直到完成。

      【讨论】:

      • +1 用于提供简单的方法,但 -1 用于使用多个具有相似值的 id,不,开个玩笑。但只是在开玩笑,关于 -1,不是关于 id 的!
      • 我正在尝试插入 Handlebars,但出现错误 -> 错误:GET localhost/connect/www/js/handlebars-v4.0.4.js
      • 好的,现在我解决了获取车把存档的问题。但是现在我的屏幕上什么都没有出现......:/我没有收到任何错误......
      • @AmandaPistolato 您是否添加了一个 id="articles" 的新 div 以显示您的文章?
      • @AmandaPistolato 你能把网页放到网上某个地方让我看看吗?
      猜你喜欢
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多