简体   繁体   English

将事件侦听器添加到动态创建的按钮

[英]Adding Event Listeners to dynamically created buttons

Working on a fun side project and ran into a little trouble.在做一个有趣的副项目时遇到了一些麻烦。 Basically, I have a page that allows a user to login to Spotify.基本上,我有一个允许用户登录 Spotify 的页面。 I then redirect them to a page that puts their top 10 artists into a card with the artists name, picture, and a little button to view upcoming shows.然后我将他们重定向到一个页面,将他们的前 10 位艺术家放入一张带有艺术家姓名、图片和一个小按钮的卡片中,以查看即将到来的节目。 I would like to link that button to a function I already wrote in another script that will pull their specified artists upcoming concerts.我想将该按钮链接到我已经在另一个脚本中编写的函数,该函数将拉动他们指定的艺术家即将举行的音乐会。

The trouble I'm running into is accessing the buttons I'm creating.我遇到的麻烦是访问我创建的按钮。 Here's the full function I'm running:这是我正在运行的完整功能:

async function fetchArtists() {
  return await fetch('https://api.spotify.com/v1/me/top/artists', settings)
  .then((response) => {return response.json()})
    .then((data) => {
      let listOfArtists = data.items.slice(0, 10).map((item) => {
        return {
         name: item.name, 
         picture: item.images[1].url
        }
      })
      //console.log(listOfArtists)
      return listOfArtists;


    }).then((listOfArtists) => {
      listOfArtists.forEach((artist) => {
        let createCard = document.createElement('div');
        createCard.class = "card"
        createCard.style = "width: 40% height: 40%"
        createCard.innerHTML = `
        <div class="row card-row justify-content-center">
          <div class="col-md-6">
            <div class="card bg-transparent text-black text-center ">
              <img src="${artist.picture}" class="card-img rounded-circle shadow-lg p-3 mb-5 bg-black rounded" alt="...">
                <div class="card-img-overlay"></div>
                  <div class="card-footer font-weight-bold bg-transparent">${artist.name}
                  <div class="row-md-6">
                    <button class="btn btn-dark">View Upcoming Shows</button>
                  </div>
                </div>
              </div>
            </div>


        let container = document.querySelector(".artist-grid")
        container.appendChild(createCard)
      })
});
}

This is working almost exactly how I want it, and outputs this: The problem is I can't seem to get an event listener to work on the buttons.这几乎完全按照我想要的方式工作,并输出以下内容:问题是我似乎无法让事件侦听器处理按钮。 I tried adding this code inside of my forEach, below the last我尝试在我的 forEach 中添加此代码,在最后一个下方

myButton = document.querySelector(".btn")
myButton.addEventListener("click, () => {
console.log("Test to see if button onclick works")

And it doesn't output anything to the console on click.它不会在单击时向控制台输出任何内容。 So I ran a console log of myButton and it showed 10 buttons, so not sure what the disconnect is if it looks seems like I am able to access them.所以我运行了 myButton 的控制台日志,它显示了 10 个按钮,所以如果看起来我可以访问它们,我不确定断开连接是什么。

perhaps it is because you forgot the double quote after click?也许是因为您在单击后忘记了双引号? myButton.addEventListener("click, () => { console.log("Test to see if button onclick works") should be replaced with myButton.addEventListener("click", () => { console.log("Test to see if button onclick works") myButton.addEventListener("click, () => { console.log("Test to see if button onclick works") 应该替换为 myButton.addEventListener("click", () => { console.log("Test to看看按钮 onclick 是否有效")

There's a few things it could be:有几件事可能是:

  • Does the button require a z-index bring it to the front?按钮是否需要z-index将其放在前面?
  • Does the button or any parent element have pointer-events: none;按钮或任何父元素是否有pointer-events: none; ? ?
  • Are you calling addEventListener after the append?你在追加之后调用addEventListener吗?
  • Has the DOM operation finished by the time you try to add the event listeners?当您尝试添加事件侦听器时,DOM 操作是否已完成?
  • You're using querySelector here but do you want to add a click listener to all buttons, or just one?您在这里使用 querySelector,但是您想为所有按钮添加一个点击侦听器,还是只添加一个?

If your problem is JS related you could try iterating over those buttons and wrapping the addEventListener operation in a timeout, so the DOM append has buffer to finish, and you can debug further, something like:如果您的问题与 JS 相关,您可以尝试遍历这些按钮并在超时中包装 addEventListener 操作,以便 DOM 追加有缓冲区可以完成,您可以进一步调试,例如:

async function fetchArtists() {
// ...

}).then((listOfArtists) => {
  // ...

  container.appendChild(createCard);

  setTimeout(() => {
    const buttons = document.querySelectorAll(`.btn`);

    buttons.forEach((button, index) => {
      console.log(`Button ${index} [query]: `, button);

      button.addEventListener(`click`, e => {
        console.log(`Button ${index} [click]: `, e);
      });
    })
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM