简体   繁体   English

如何使用JQuery为数组的每个值生成HTML元素?

[英]How do I generate the HTML element for every value of the array with JQuery?

Here is my HTML element : 这是我的HTML元素:

        <li class="comment author-comment">

                <div class="info">
                    <a href="#">Jack Smith</a>
                    <span>3 hours ago</span>
                </div>

                <a class="avatar" href="#">
                    <img src="{{ 
            asset('commentui/images/avatar_author.jpg') }}" width="35" 
             alt="Profile Avatar" title="Jack Smith" />
                </a>

                <p>Value is here</p>

      </li>

Here is my JQuery code : 这是我的JQuery代码:

   $.get('{{ URL::to('comment/retrive') }}',function(data){
    console.log(data);
      $.each(data, function(key, value){
      $('.comment p').html(value.comment);
    });
   });

I need to generate The HTML Element with every value of the data or value.comment. 我需要用数据或value.comment的每个值生成HTML元素。 So that it creates a list of the values, But now I am getting only the first one value. 这样就可以创建一个值列表,但是现在我只得到第一个值。 Please help. 请帮忙。

The data is retriving an object as the image here and I need to print the comment only in list : 数据正在检索一个对象作为此处的图像,我只需要在list中打印注释: 在此处输入图片说明

Replace 更换

$('.comment p').html(value.comment);

By 通过

$('.comment p').append(value.comment);

Because with .html each loop will override the previous one. 因为使用.html,每个循环都将覆盖前一个循环。

But Append will add your value after the previous. 但是Append会在前一个之后添加您的值。

You have to create a new element for each line, not just update your single element text value : 您必须为每一行创建一个新元素,而不仅仅是更新单个元素的文本值:

var rp=$('.comment p');
$.each(data, function(key, value){
  var p = $('<p>');
  rp.append(p);
  p.text(value.comment);
});

尝试附加数据而不是替换数据。

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

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