在下面的代码片段中,预期的行为是单击“播放”,然后播放 mp3,并将“播放”更改为“正在播放”。然而,在我当前的浏览器(Mozilla、Safari)中,我得到以下信息:当单击“播放”时,它会转换为“正在播放”,但没有播放任何文件。然后,仅当单击“播放”时才会播放该文件。为什么我必须点击两次?注释掉“document.getElementById('player').innerHTML = 'playing';”行时第一次点击后文件会立即播放。
<!doctype html>
<html>
<body>
<div id="player">Play</div>
<script>
audioEl = document.createElement("audio");
audioEl.setAttribute('src','audioFile.mp3');
document.getElementById('player').appendChild(audioEl);
document.getElementById('player').addEventListener('click',function() {
document.getElementById('player').innerHTML = 'playing';
audioEl.play();
});
</script>
</body>
</html>
最佳答案
innerHTML
替换元素的所有内容,而不仅仅是文本。创建audio
后标签,您的 HTML 看起来像这样:
<!doctype html>
<html>
<body>
<div id="player">Play
<audio src='audioFile.mp3'>
</div>
</body>
</html>
所以当你将div的内容替换为playing
时您删除 <audio src='audioFile.mp3'>
.
您必须像这样为 div 中的文本添加一个元素
<div id="player">
<div id="player-text"></div>
</div>
并使用这个 JavaScript
audioEl = document.createElement("audio");
audioEl.setAttribute('src','audioFile.mp3');
document.getElementById('player').appendChild(audioEl);
document.getElementById('player').addEventListener('click',function() {
document.getElementById('player-text').innerHTML = 'playing';
audioEl.play();
});
关于javascript - 带有音频和innerHTML 的点击回调无法按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41796385/