首页 > 解决方案 > getElementById for button that is dynamically created

问题描述

I want to be able to do stuff after a button is clicked, but the button is dynamically created and when I try to access the button by ID it returns null.

I'm using a base script and editing it, so I'm not sure how to access the element with the way the template html is loading.

Here is what I have, and where I am trying to access the element

var mainContainer = document.getElementById('js-main-container'),
loginContainer = document.getElementById('js-login-container'),
loginButton = document.getElementById('js-btn-login'),
background = document.getElementById('js-background');

var spotifyPlayer = new SpotifyPlayer();
var spotifyApi = new SpotifyWebApi();

var template = function (data) {
return `
  <div class="main-wrapper">
    <div class="now-playing__img">
      <img src="${data.item.album.images[0].url}">
    </div>
    <div class="now-playing__side">

//======button i want to access
      <button class="btn btn--play" id="js-btn-play">Play a song</button>

      <div class="now-playing__name">${data.item.name}</div>
      <div class="now-playing__artist">${data.item.artists[0].name}</div>
      <div class="now-playing__status">${data.is_playing ? 'Playing' : 'Paused'}</div>
      <div class="progress">
        <div class="progress__bar" style="width:${data.progress_ms * 100 / data.item.duration_ms}%"></div>
      </div>
    </div>
  </div>
  <div class="background" style="background-image:url(${data.item.album.images[0].url})"></div>
`;
};

spotifyPlayer.on('update', response => {
mainContainer.innerHTML = template(response);

});

spotifyPlayer.on('login', user => {
if (user === null) {
  loginContainer.style.display = 'block';
  mainContainer.style.display = 'none';
} else {
  loginContainer.style.display = 'none';
  mainContainer.style.display = 'block';
  spotifyApi.setAccessToken(spotifyPlayer.accessToken);

  var playContainer = document.getElementById("js-btn-play");

  playContainer.addEventListener('click', () => {
    // ======Do Stuff here, but playContainer is null
  });
}
});

loginButton.addEventListener('click', () => {
  spotifyPlayer.login();
});
spotifyPlayer.init();

Edit: HTML

<!doctype html>
<html lang="en">
<head>
  <title>Spotify Application</title>
<link rel="stylesheet" type="text/css" href="static/css/style.css">

</head>
<body bgcolor=white>

<div class="container">
  <div class="login-container hidden" id="js-login-container">
    <button class="btn btn--login" id="js-btn-login">Login with Spotify</button>
  </div>
<div class="main-container hidden" id="js-main-container"></div>
</div>

<script src="https://spotify-player.herokuapp.com/spotify-player.js"></script>
<script type="text/javascript" src="static/js/spotify-web-api-js.js"></script>
<script type="text/javascript" src="static/js/script.js"></script>
</body>

标签: javascripthtml

解决方案


推荐阅读