如何在循环中的每个迭代中包含玉模板?

时间:2018-08-03 19:31:34

标签: javascript node.js api express pug

我正在尝试在循环中的每个迭代中包含相同的Jade模板,以便用户单击按钮时,无论哪个迭代,它都提供相同的模板。这是我正在创建的博客引擎。我想为每个帖子都包含一个deletePostModal.jade模板,当在特定帖子上单击按钮时,模态会出现,并带有删除该帖子的选项。仅在第一篇文章上单击按钮时,才会出现模式对话框!这是我的blog.jade代码:

      each post in postsList
        div#post-container(class='container-fluid')
          .row
            .col-md-6
              a(href='/blog/posts/#{post._id}')  
                h2 #{post.title}
                h4 Date and Time posting
                img#post-img(src=urlList[i])
            .col-md-1.offset-md-5
              if isAdmin
                include ./includes/deletePostModal.jade // Template I'm trying to include                   
                button.xxx#deletePostBtn X // Button to add template
          .row
            .col-md-12
              div#content-text-container
                p(id='content-text') 
                  | #{post.content}
          - i++

我的deletePostModal.jade代码:

#deletePostModal.modal
  // Modal content
  .modal-content
    .modal-header
      span.closeDeletePost ×
      h2 Modal Header
    .modal-body
      p Are you sure you want to delete post?
    .modal-footer
      a(href="api/blog/posts/#{post._id}/delete")
        button Yes
      button.closeDeletePost No

还有我的deletePostModal.js代码:

// Get the modal
var deletePostModal = document.getElementById('deletePostModal');

// Get the button that opens the modal
var deletePostBtn = document.getElementById("deletePostBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("closeDeletePost")[0];

// When the user clicks the button, open the modal
deletePostBtn.onclick = function() {
      deletePostModal.style.display = "block";
};

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
      deletePostModal.style.display = "none";
};

这是我完成博客的最后一步,而且我已经花了好几个小时不停地动脑子。感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我猜是因为您有多个具有相同id的按钮。

在帖子中循环浏览时在button.xxx#deletePostBtn中创建。

然后当您通过ID获取元素

// Get the button that opens the modal var deletePostBtn = document.getElementById("deletePostBtn");

它仅适用于第一篇文章,因为那是它抓住的那篇文章。

尝试为每个按钮添加唯一的ID。使用帖子ID或类似的名称。