javascript - 每 5 秒随机发声
问题描述
我试图每 5 秒生成一次随机声音,我的问题是从 javascript 中的 html 更改音频标签中的 src(请参阅代码)我收到此错误 Uncaught TypeError: Cannot set property 'src' of 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 中可能有一些重复的 ID。
- 您的 HTML 中某处存在语法错误。
如果在这些检查之后这些问题仍然存在,那么我怀疑您是getElementById
在加载 HTML 之前调用的。为了解决这个问题,我将 JS 代码包装在一个事件监听器中,用于“加载”事件,如下所示:
<!-- 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
,它做同样的事情:
<!-- 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>
推荐阅读
- c++ - 如何在 arduino 程序中存储 JSON 数组?
- php - 从字符串中提取数据
- c# - 无法使用 Selenium webdrive (c#) 选择复选框
- javascript - 如何在圆形图像中使用 CSS 制作彩虹边框?
- c# - 在 Excel 互操作对象的合并行中自动调整文本。C#
- c# - ASP.NET Core MVC 路由到带有参数的 url
- arrays - 多维数组上的 Fortran 操作 - 求和示例
- java - Spring-Cloud-Stream Kafka Azure - 获取数据时出现意外错误代码 13
- javascript - 本地主机的CORS问题?
- java - 链两个答案单