未捕获的类型错误:无法在 playVid 处读取 null 的属性“play”

我收到播放和暂停错误。两者都显示“Uncaught TypeError: Cannot read property 'play' of null at playVid”


我的代码如下,我不确定我做错了什么。


<button onclick="playVid()"  type="button">Play Video</button>

<button onclick="pauseVid()" type="button">Pause Video</button><br> 


<video id="myVideo" width="320" height="176">

  <source src="<?php echo $video ?>" type="video/mp4">

</video>


var vid = document.getElementById("myVideo");


function playVid() {

  vid.play();

}


function pauseVid() {

  vid.pause();

}


function menuAnimate(x) {

  $(".menu-wrap").toggleClass("open");

}


守候你守候我
浏览 122回答 1
1回答

富国沪深

始终在加载所有 HTML 元素后运行脚本第一次运行脚本时会发生什么var vid = document.getElementById("myVideo");由于元素的主体未加载,因此不存在具有 id 的元素,myVideo并且 vid 被初始化为null现在,当您单击按钮时,会调用该按钮,但由于初始化为 null,因此playVid()无法执行vid.play()vid<!DOCTYPE html><html><head>&nbsp;<title>Document</title></head><body>&nbsp;&nbsp;&nbsp; <button onclick="playVid()"&nbsp; type="button">Play Video</button>&nbsp; <button onclick="pauseVid()" type="button">Pause Video</button><br>&nbsp;&nbsp; <video id="myVideo" width="320" height="176">&nbsp; &nbsp; <source src="<?php echo $video ?>" type="video/mp4">&nbsp; </video>&nbsp; <script>&nbsp; &nbsp; var vid = document.getElementById("myVideo");&nbsp; &nbsp; function playVid() {&nbsp; &nbsp; &nbsp; vid.play();&nbsp; &nbsp; }&nbsp; &nbsp; function pauseVid() {&nbsp; &nbsp; &nbsp; vid.pause();&nbsp; &nbsp; }&nbsp; &nbsp; function menuAnimate(x) {&nbsp; &nbsp; &nbsp; $(".menu-wrap").toggleClass("open");&nbsp; &nbsp; }&nbsp; </script></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP