首页 > 解决方案 > 每 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"
/>

标签: javascripthtmlaudio

解决方案


document.getElementById("song-generator")评估的事实null告诉我一些可能的事情:

  1. 您的 HTML 中可能有一些重复的 ID。
  2. 您的 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>


推荐阅读