javascript - 在保留关联事件的同时将 javascript 元素转换为 html
问题描述
我直接在javascript中创建了一个复选框,并通过以下方式绑定了一个点击事件:
let checkBox = document.createElement('input');
checkBox.onclick = (e) => {
console.log("click", e);
};
现在我想将此元素转换为纯 html,同时保留关联的事件。我现在可以调用 checkBox.outerHTML 来获取关联的 html,但该事件会消失。
有没有办法在不删除附加事件的情况下做同样的事情?
解决方案
推荐的方式是这样
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>
推荐阅读
- flutter - 状态不变(停留在初始状态)
- python - Pandas 检查给定列表中是否存在单元格中的单词(在许多单词中)
- react-native - React Native Pod 错误 - [!] 无效的 `Podfile` 文件:767:'' 处的意外令牌。| 相关问题 #448
- javascript - 将数组索引处的值更改为 falsey 会使数组稀疏吗?
- typescript - 泛型类型的 TypeScript 部分
- r - 在闪亮的服务器上找不到返回的 rmarkdown
- python - 如何检查对象是否为 np.array()?
- angular - 如何使用 php 后端更新 Angular Reactive 表单
- swift - URLSession.shared.dataTaskPublisher 在 IOS 13.3 上不起作用
- python - Django - 保存用户后获取用户ID