javascript - 如何将项目附加到现有 Handlebars 模板中的列表?

标签 javascript jquery templates handlebars.js

我正在尝试在现有 Handlebars 模板中附加一个列表。下面的代码允许我添加评论,但为了使新评论与现有评论一起出现在列表中,我需要刷新。我想知道如何将新评论附加到模板中现有的评论列表中。我已经包含了整个模板,但我尝试添加新评论的地方是 id 为 bodyOfComments 的 ul。谢谢您的帮助。

 var comment_post = function() {

    // console.log($(this).attr("data-id"))
    $.ajax({
        url: 'http://localhost:3000/comments',     
        type: 'POST',
        data: {comment: {
            body: $('#content').find('input[name="createComment"]').val(),
            user_id: 1,
            image_set_id: $(this).attr("data-id")}
        }
    }).done(function(response) {
        console.log(response);
        var template = Handlebars.compile($('#imageSetTemplate').html());
          $('#bodyOfComments').append(template({
            comment: response
        }));

    });
};
$(document).ready(function () {
  $('#content').on('click', '#submitComment', comment_post)
});

下面的代码是html文件中的 Handlebars 模板

<script id="imageSetTemplate" type="text/x-handlebars-template">

    <h1>{{image_set.voting_criteria}}</h1>


    <div class="continer">
      <div class="row">
        {{#each image_set.images}}
        <div class = "col-xs-4"><img src={{this.image_url}}></div>
        {{/each}}
      </div>
    </div>

    <ul id="bodyOfComments">
      {{#each image_set.comments}}
        <li> {{this.body}} </li>
      {{/each}}
    </ul>

    <button type="submit" id="submitComment" data-id={{image_set.id}}>Create Comment</button>
    <input name="createComment" id="commentBody">




</script>

最佳答案

将评论模板移出作为单独的模板。

<script id="commentsTemplate" type="text/x-handlebars-template">
    {{#comments}}
      <li> {{.}} </li>
    {{/comments}}
</script>

然后您可以按如下方式附加。

var template = Handlebars.compile($('#commentsTemplate').html());
  $('#bodyOfComments').append(template({
    comments: response
  }));

关于javascript - 如何将项目附加到现有 Handlebars 模板中的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26879327/

相关文章:

javascript - 在 Visual Studio Code 中提取 JS/TS 中的局部变量的键盘快捷键

javascript - 如果 div 滚动大于 - JS 事件

html - 在 Angular 2 中使用没有额外元素的 ngIf

c++ - 带有运算符 ">>"的 typedef 是什么意思?

c++ - 具有完整类型信息的循环依赖

javascript - 使用 Jquery/Javascript 将 imgsrc 值发送到隐藏字段

javascript - 将 JSON 值保存为另一个 JSON 文件

javascript - Bootstrap 3 : Fixed navbar in mobile layout is expanded by default on load without 'in' class

jquery - 将变量传递给 .animate() 函数 JQuery

javascript - 取消选中复选框时 AJAX 不起作用