修改 <source> 元素的 src 属性 后视频没有更新

Video doesn't update after modifying the src property of its <source> element

我正在尝试更改 <video> 的来源,但它没有播放新视频:

<body onload="setvid()">
    <div id="container">
            <video width="640" height="360" autoplay loop>
                <source id="srcc" src="" type="video/mp4">
            </video>
    </div>
    <script type="text/javascript">
        function setvid() {
            document.getElementById("srcc").src = "vid" + Math.floor(Math.random() * 10) + ".mp4";
        }
    </script>
</body>

有什么建议吗?

来自 specification(强调我的):

The src attribute gives the address of the media resource. The value must be a valid non-empty URL potentially surrounded by spaces. This attribute must be present.

Note: Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unnecessarily complicated approach.

看来您应该将新源分配给 <video> 元素。

<div id="container">
        <video width="640" height="360" autoplay loop />
</div>
<script type="text/javascript">
    function setvid() {
        document.querySelector('video').src = "...";
    }
</script>

正如 Felix 所说,根据 this 规范说明,您不应该尝试更改源元素的 src 属性。

相反,假设您有:

<audio>
    <source src='./first-src'/>
</audio>

您可以像这样修改媒体源:

<audio src='./second-src'/>
    <source src='./first-src'/>
</audio>