使用 javascript 迭代 NodeList 时无法添加事件

Can't add event when iterate a NodeList using javascript

提问人:Khaled Boussoffara 提问时间:2/23/2023 最后编辑:Khaled Boussoffara 更新时间:2/23/2023 访问量:30

问:

我正在尝试使用 javascript 迭代一个 NodeList 对象,并且我想将 click 事件用于 eatch 项目:

document.addEventListener("DOMContentLoaded", async () => {
try {

    posts.map(post => {
        container.innerHTML += outPutHtml(post); // user-interaction elements are created with ajax request 
} catch (e) {
    console.error(e);
   
} finally {
    highlight.highlightAll();

});

const elements = document.querySelectorAll(".user-interaction");

console.log(elements); //   NodeList []length: 0[[Prototype]]: NodeList
console.log(typeof elements); // object

elements.forEach(function(element) {
    element.addEventListener("click", function() {
        console.log('ok');
    });
});

元素上的点击事件不起作用!

我该如何解决这个问题?

JavaScript ajax dom foreach addeventlistener

评论

0赞 Code Spirit 2/23/2023
您的列表为空(长度:0),这意味着在执行脚本时未找到具有 className 的元素。.user-interaction

答:

0赞 Denis Rudov 2/23/2023 #1

const addListeners = () => {
  const elements = document.querySelectorAll(".user-interaction");

  console.log(elements); //   NodeList []length: 0[[Prototype]]: NodeList
  console.log(typeof elements); // object

  elements.forEach(function(element) {
    element.addEventListener("click", function() {
      console.log('ok');
    });
  });
};

async function makeAjaxrequest() {
  return new Promise((resolve) => {
    setTimeout(resolve, 2000);
  })
}




const runTheApp = async() => {
  console.log('start')
  await makeAjaxrequest();
  console.log('done')
  addListeners();
}


runTheApp();
.user-interaction {
  cursor: pointer;
}
<div class="user-interaction">1</div>
<div class="user-interaction">2</div>
<div class="user-interaction">3</div>

将你的逻辑包装起来

window.addEventListener('DOMContentLoaded', (event) => {
   console.log('your logic here')
});

评论

0赞 Khaled Boussoffara 2/23/2023
我更新了我的问题,用户交互元素是通过异步ajax请求获取的,我该如何添加clik事件?
0赞 Khaled Boussoffara 2/23/2023
当我将代码放在 finally 块中时,它可以工作