gpt4 book ai didi

javascript - 每5秒随机发出一声声音

转载 作者:行者123 更新时间:2023-12-02 23:30:42 25 4
gpt4 key购买 nike

我试图每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中可能有一些重复的ID。
  • HTML的某个地方存在语法错误。

  • 如果经过这些检查后这些问题仍然存在,那么我怀疑您是在加载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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com