javascript - DOM getElementById 作为获取整个元素
问题描述
为什么礼物不只是得到div id?
单击模态会返回整个 div 而不仅仅是 id,这是为什么呢?
function Modals(id, bt, show) {
const modal = document.getElementById(id)
modal.classList.add(show)
modal.addEventListener("click", (elemento) => {
if (elemento.target.id === modal) {
modal.classList.remove(show)
console.log(modal)
}
})
}
const comentarios = document.querySelector(".bt_comentarios")
comentarios.addEventListener("click", () => Modals("modal_comentarios",
"bt_comentarios", "show"))
<div id="modal_comentarios" class="modal fix"></div>
解决方案
document.getElementById
将返回HTMLElement
. 要获取元素的 id,您需要使用该id
属性。
const main = document.getElementById('main');
console.log(main);
console.log(main.id);
<div id="main">
</div>
使用您的代码段
function Modals(id, bt, show) {
const modal = document.getElementById(id)
modal.classList.add(show)
modal.addEventListener("click", (elemento) => {
// EDIT: I used modal.id
if (elemento.target.id === modal.id) {
modal.classList.remove(show)
// EDIT: I used modal.id
console.log(modal.id)
}
})
}
const comentarios = document.querySelector(".bt_comentarios")
comentarios.addEventListener("click", () => Modals("modal_comentarios",
"bt_comentarios", "show"))
<div id="modal_comentarios" class="modal fix">
<button id="modal_comentarios" class="bt_comentarios">Click Me!</button>
</div>
我改变了什么
我添加了几部分以使代码沿着 if 语句的路径运行,并引用modal.id
属性而不是自身的实例HTMLElement
。如果您有更多问题,请告诉我。
推荐阅读
- debugging - 如何生成仅在失败时才详细的 make 构建
- javascript - 从将所有文件转换为 es6 的项目中删除 Typescript
- python - Panda Pivot 功能无法正常工作
- razor - SfGrid RowSelection 事件处理重新加载数据
- python - 如何从 Django“Choices”中获取值并通过下拉元素将它们作为 Axios 请求发送到 React 前端?
- python - 使用 keras 预处理后绘制图像
- graphql - GraphQL:在所有解析器之间共享上下文
- linux - 安装pdftk alpine linux时出现不可满足的约束错误
- python - 为什么 DataFrame.drop() 不适用于列方式(轴 = 1)?
- django - 如何在 django 迁移中将模型字段的值拆分为多个模型字段?