首页 > 解决方案 > DOM getElementById 作为获取整个元素

问题描述

为什么礼物不只是得到div id?

单击模态会返回整个 div 而不仅仅是 id,这是为什么呢?

js文件

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>

标签: javascript

解决方案


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。如果您有更多问题,请告诉我。


推荐阅读