如何在允许听众工作的同时将HTML附加到div?

时间:2018-04-27 09:15:20

标签: javascript dom

我有以下HTML要附加到div:

var map_div =
"<div class=\"maps\">"
  + "<h2>View marker <button class=\"close\" data-what=\"maps\">[ close ]</button></h2>"
  + "<div class=\"the-contents\" id=\"mapDiv" + link_id + "\"></div>"
+ "</div>";

我可以这样做:

document.getElementById("listing"+link_id).insertAdjacentHTML('beforeend', map_div );

这会将HTML正确添加到div中 - 但是这有一个问题,因为它似乎不会让侦听器保持在 button.close 。如果我将HTML直接放在原始代码中(并且不要尝试将其注入DOM),这样可以正常工作。有什么我想念的吗?我是否需要创建每个单独的元素,然后通过appendChild添加它,然后将另一个元素添加到该新元素中?似乎有点啰嗦:/

由于

1 个答案:

答案 0 :(得分:1)

您可以向容器添加侦听器并使用自定义属性来标识元素的角色和ID:

&#13;
&#13;
document.querySelector("button").addEventListener(
  "click",
  e=>addItem(++startID)
)

var startID=0;
const container = document.getElementById("container");
const addItem = itemID => {
  const el = document.createElement("div");
  el.innerHTML = `
  <a href="#" data-role="say-hi" data-id="${itemID}">say hi</a>
  <a href="#" data-role="remove" data-id="${itemID}">remove</a>
  ${itemID}
  `;
  el.setAttribute("data-link-container-id",itemID);
  container.appendChild(el);
}

const handleClickable = e => {
  e.preventDefault();
  const id= e.target.getAttribute("data-id");
  console.log("hello:",id);
}
const handleRemove = e => {
  e.preventDefault();
  const id= e.target.getAttribute("data-id");
  container.querySelector(`[data-link-container-id="${id}"]`).remove();
}
//add event listener to container and use data-role to see what's clicked
container.addEventListener(
  "click",
  e=>{
    const role = e.target.getAttribute("data-role");
    if(role==="say-hi"){
      return handleClickable(e);
    }
    if(role==="remove"){
      return handleRemove(e);
    }
  }
)
&#13;
<div id="container">
  <button>add</button>
</div>
&#13;
&#13;
&#13;