首页 > 解决方案 > 在保留关联事件的同时将 javascript 元素转换为 html

问题描述

我直接在javascript中创建了一个复选框,并通过以下方式绑定了一个点击事件:

let checkBox = document.createElement('input');
checkBox.onclick = (e) => {
  console.log("click", e);
};

现在我想将此元素转换为纯 html,同时保留关联的事件。我现在可以调用 checkBox.outerHTML 来获取关联的 html,但该事件会消失。

有没有办法在不删除附加事件的情况下做同样的事情?

标签: javascripthtmldom-events

解决方案


推荐的方式是这样

window.addEventListner("load",function() {
  document.getElementById("checkboxContainer")
    .addEventListener("click",function(e) { 
    const tgt = e.target; 
    if (tgt.type && tgt.type==="checkbox") {
      console.log("click",tgt) 
    }
  });
});

现在您可以在加载之前或之后创建您的复选框

window.addEventListener("load", function() {
  const container = document.getElementById("checkboxContainer");
  container.addEventListener("click", function(e) {
    const tgt = e.target;
    if (tgt.type && tgt.type === "checkbox") {
      console.log("click", tgt)
    }
  });
  const inp = document.createElement("input")
  inp.type = "checkbox";
  inp.value = "dynamic";
  container.appendChild(inp);
});
<div id="checkboxContainer">
  <input type="checkbox" value="static" />
</div>


推荐阅读