javascript - jQuery - 为每个对象创建新的 div?

标签 javascript jquery html json for-loop

我有一个html代码块

<div class="modal-comment-content">
      <ul class="list-inline">
        <li><a href="#"><img src="/defaultpic.jpg" width="100" class="img-circle"></a></li>
        <li>
          <ul class="list-unstyled">
            <li><a href="#" class="comment_username">John D.</a></li>
            <li class="comment_created_at">~ 4 hours ago</li>
          </ul>
        </li>
      </ul>
      <p class="comment_comment">This is a completely random sentence. This is the second sentence. Closing sentence right here.</p>
      <hr>
</div>

我有一个遍历对象数组的 for 循环。

for (var i = 0; i < json.length; i++)
    {
      var user = json[i].user.first_name + ' ' + json[i].user.last_name.charAt(0) + '.';
      var comment     = json[i].comment;
      var created_at  = json[i].created_at;

    }

我想将 html 代码块用作数组对象每次迭代的"template"。关于如何完成的任何想法?问候,

最佳答案

如果您使用的是 Angular JS,则始终存在 NG 重复标记并将 HTML 代码(这是您的模板)绑定(bind)到模型。这是文档:

https://docs.angularjs.org/api/ng/directive/ngRepeat

如果你只是想快速破解,并且对框架的​​使用不感兴趣,你总是可以做这样的事情

// create the template variable using your div content and some special tokens
var template = '<div class="modal-comment-content">
  <ul class="list-inline">
    <li><a href="#"><img src="%USER_IMAGE%" width="100" class="img-circle"></a></li>
    <li>
      <ul class="list-unstyled">
        <li><a href="#" class="comment_username">%USERNAME%</a></li>
        <li class="comment_created_at">%CREATED_AT%</li>
      </ul>
    </li>
  </ul>
  <p class="comment_comment">%COMMENT%</p>
  <hr>
</div>';

var jLen  = json.length;
var parentDiv = $('#parentDiv');

// create and attach a new 'Div' to some parent
// using the template, replacing the tokens with dynamic values from the list.
for (var i = 0; i < jLen; ++i)
{
  var user = json[i].user.first_name + ' ' + json[i].user.last_name.charAt(0) + '.';
  var comment     = json[i].comment;
  var created_at  = json[i].created_at;
  var divContent = template.replace('%COMMENT%', comment).replace('%CREATED_AT%', created_at).replace('%USERNAME%', user);

  parentDiv.append(divContent);
}

关于javascript - jQuery - 为每个对象创建新的 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35421791/

相关文章:

javascript - 名称中带有空格的关联数组不会出现

javascript - 容器内没有填充的 Highchart

jquery - HTML/jQuery - 防止空文本节点

javascript - 无法在 superslides jquery 插件上加载 ajax 内容

javascript - 无论我做什么,可调整大小的 div 都不起作用

javascript - Vue.js 修改计算属性?

javascript - 每次渲染组件时调用一个函数,因为 componentDidMount() 只触发一次

javascript - append 多个元素的推荐方法

jquery - Materialise DatePicker 覆盖 jQuery DatePicker

jquery - select2 的编程选择,通过 Ajax 检索其数据