簡體   English   中英

在 dom 中呈現元素后,事件偵聽器不起作用

[英]Event listener not working after elements are rendered in the dom

我正在創建一個項目,當我單擊某個類別卡時,我會獲得該類別的 ID 並重定向到電影屏幕。

我知道 index.js 中的row.eventlistener()它將在呈現元素之前執行,這就是它不選擇 id 的原因。 在將其添加到容器之前,我應該如何將事件偵聽器添加到每個新呈現的項目,以便我可以獲得每個類別卡的 id。

index.js

async function getCategories() {
  let url = 'http://localhost:8080/movieCategories';
  try {
    let res = await fetch(url);
    return await res.json();
  } catch (error) {
    console.log(error);
  }
}


async function renderCategories() {
  let categories = await getCategories();
  let html = '';
  categories.forEach(category => {


    let htmlSegment = `
            <div class="category-card" id=${category.id}>
            <img src="./assets/images/sci-fi.jpg" alt="" class="card-img">
            <div class="name">${category.name}</div>
          </div>
        `;
    html += htmlSegment;
  });
  let container = document.querySelector('.category-grid');
  container.innerHTML = html;
}

 renderCategories();


document.querySelectorAll('div.category-card').forEach(row=>{
  row.addEventListener('click',event=>{
    console.log('Category clicked', event.currentTarget.id)
    window.location= 'movies.html?categoryId=' +event.currentTarget.id;
  });

});

索引.html

<section class="category" >
  <h2 class="section-heading">Category</h2>
  <div class="category-grid">
  </div>
</section>

您不是在等待對renderCategories的調用,而是在renderCategories方法中移動您的事件偵聽器邏輯,或者您可以使用立即調用的異步函數表達式或簡稱 IIAFE,更多關於這里的信息immediate-invoked-async-function-expression

    (async () => {
        await renderCategories();
        document.querySelectorAll('div.category-card').forEach(row => {
           row.addEventListener('click', event => {
               console.log('Category clicked', event.currentTarget.id)
               window.location= 'movies.html?categoryId=' +event.currentTarget.id;
           });
        });
    })();

您也可以在創建事件時直接在 div 本身上添加事件並傳遞 id 或任何您想要的。

<div class="category-card" id=${category.id} onclick="onCatClick(${category.id})">

在此之后,您可以在頂級onCatClick函數中移動您的邏輯。

function onCatClick(id) {
    console.log('Category clicked', id)
    window.location= 'movies.html?categoryId=' + id;
}

這是如果您的樣式/布局不允許您使用錨元素。 否則,您可以簡單地將 div 替換為錨元素:

<a href="movies.html?categoryId=${id}"></a>

嘗試:

async function getCategories() {
  let url = 'http://localhost:8080/movieCategories';
  try {
    let res = await fetch(url);
    return await res.json();
  } catch (error) {
    console.log(error);
  }
}


async function renderCategories() {
  let categories = await getCategories();
  let html = '';
  categories.forEach(category => {


    let htmlSegment = `
            <div class="category-card" id=${category.id}>
            <img src="./assets/images/sci-fi.jpg" alt="" class="card-img">
            <div class="name">${category.name}</div>
          </div>
        `;
    html += htmlSegment;
  });
  let container = document.querySelector('.category-grid');
  container.innerHTML = html;
}
 //es8
await renderCategories();

// fix timeout async render element
setTimeout(() => {
  document.querySelectorAll('div.category-card').forEach(row=>{
    row.addEventListener('click',event=>{
      console.log('Category clicked', event.currentTarget.id)
      window.location= 'movies.html?categoryId=' +event.currentTarget.id;
    });
  })
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM