我希望能够在单击按钮后执行操作,但是按钮是动态创建的,当我尝试按ID访问按钮时,它返回null。
我正在使用基本脚本并对其进行编辑,因此我不确定如何使用模板html加载的方式访问该元素。
以下是我的内容,以及我尝试访问该元素的位置
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();
修改: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>