从数组(JS)删除特定注释

时间:2019-03-19 21:09:34

标签: javascript dom rendering

我有一个模块,可将“ posts”数组(来自另一个.js文件)呈现到DOM。 其中一项功能是在单击图标旁的特定注释时将其删除。 我知道我需要给他们一个可以识别并建立图标注释连接的类,但似乎无法完成。 有人可以帮忙吗?

posts数组的示例:

let _posts = [
    {
        text: "First post!",
        id: "p1",
        comments: [
            { id: "c1", text: "First comment on first post!" },
            { id: "c2", text: "Second comment on first post!!" },
            { id: "c3", text: "Third comment on first post!!!" }
        ]
    },
    {
        text: "Aw man, I wanted to be first",
        id: "p2",
        comments: [
            { id: "c4", text: "Don't wory second poster, you'll be first one day." },
            { id: "c5", text: "Yeah, believe in yourself!" },
            { id: "c6", text: "Haha second place what a joke." }
        ]
    }
]

渲染模块本身:

const Renderer = function() {
  const renderPosts = function(posts) {
    $("#posts").empty()

    for (index in posts) {
      let newDiv = $(`<div class=post><div class=post-text id=${posts[index].id}>${posts[index].text}
                </div>`)
      $("body").append(newDiv)
      for (let index2 in posts[index].comments) {

        let newDiv2 = $(`<div class=comments id=${posts[index].comments[index2].id}><i id="delete-comment" class="fas fa-minus-circle"></i> ${posts[index].comments[index2].text}</div></div>`)
        $(`#${posts[index].id}`).append(newDiv2)
        let $deleteComment = $(".comments")

        $("body").on("click", "#delete-comment", function() {
          $deleteComment.remove();
        });

      }
    }

  }
  return {
    renderPosts
  }
}

非常感谢和抱歉,如果一开始代码格式化不顺利,我找不到一种将所有字符按我想要的方式移动的方法。如有需要,将在您的帮助下进行编辑

1 个答案:

答案 0 :(得分:1)

ID应该是唯一的,您不应该在每个帖子中都使用id="delete-comment"。那应该是一堂课。

我已经向删除按钮添加了data-id属性,其中包含评论的ID。

使用事件委托时,只需执行一次,而无需在创建元素的循环内进行。

const Renderer = function() {
  const renderPosts = function(posts) {
    $("#posts").empty()
    for (index in posts) {
      let newDiv = $(`<div class=post><div class=post-text id=${posts[index].id}>${posts[index].text}
                </div>`)
      $("body").append(newDiv)
      for (let index2 in posts[index].comments) {
        let newDiv2 = $(`<div class=comments id="${posts[index].comments[index2].id}"><i class="fas fa-minus-circle delete-comment" data-id="${posts[index].comments[index2].id}"></i> ${posts[index].comments[index2].text}</div></div>`);
        $(`#${posts[index].id}`).append(newDiv2);
      }
    }
  }
  return {
    renderPosts
  }
}

$("body").on("click", ".delete-comment", function() {
  $(`#${$(this).data('id')}`).remove();
});