我试图每5秒产生一次随机声音,而我的问题是从javascript中的html更改音频标签中的src(请参见代码)
我收到这个错误
未捕获的TypeError:无法将属性'src'设置为null
谁能向我解释我在做什么错?
(JS)
document.getElementById("song-generator").src = "test.mp3";
(html)
<embed
id="song-generator"
hidden="true"
name="test"
src=""
loop="true"
autostart="true"
/>
最佳答案
document.getElementById("song-generator")
评估为null
的事实告诉我一些可能的事情:
如果经过这些检查后这些问题仍然存在,那么我怀疑您是在加载HTML之前调用
getElementById
。为了解决这个问题,我将JS代码包装在'load'事件的事件监听器中,如下所示:<!-- Either put your actual JS code here, or link a script -->
<script>
window.addEventListener("load", () => {
//put business logic here
document.getElementById("song-generator").src = "test.mp3";
});
</script>
另外,您可以使用
window.onload
,它可以执行the same thing:<!-- Either put your actual JS code here, or link a script -->
<script>
window.onload = () => {
//put business logic here
document.getElementById("song-generator").src = "test.mp3";
});
</script>
关于javascript - 每5秒随机发出一声声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53966066/