【问题标题】:addEventListener not working for dynamic buttonaddEventListener 不适用于动态按钮
【发布时间】:2021-12-09 18:39:50
【问题描述】:

我有一个动态制作的按钮,我已经设置了 id 和 class 以尝试设置 addEventListener 但在 DOM 中未读取 addEventListener 但 ID 和 class 是。

这是我的代码

 let button: HTMLButtonElement = document.createElement('button')

  button.id = "comment-button";
  button.className = "comment-button"; 

(ID 和班级正在工作)

这是我尝试过的:

  button.addEventListener("click", setComment);

  document.getElementById("comment-button")?.addEventListener("click", setComment);

【问题讨论】:

标签: javascript typescript button addeventlistener


【解决方案1】:

要从文档中检索元素,您需要将创建的元素实际添加到文档中。 document.body.appendChild(button)

【讨论】:

  • 该按钮已添加到页面中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-10
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多