JavaScript 'x is not a function'

标签 javascript html

我正在尝试使用两个单独的按钮开始和停止两个视频。我只是复制了代码并重命名了变量,但一段代码可以工作,而另一段则不能。我收到错误“TypeError:video2.pause 不是 HTMLButtonElement.c 中的函数”。视频和按钮都分别放置在模态中。为什么我会收到这个奇怪的错误,尤其是当完全相同的代码工作时?

Javascript:

    var video = document.getElementById("video.mp4");
    var playButton = document.getElementById("play-pause");

    var video2 = document.getElementById("video2.mp4");
    var play = document.getElementById("play-pause2");

    playButton.addEventListener("click", function a () {
        if (video.paused == true) {
          video.play();
          playButton.innerHTML = "Pause";
        } else {
          video.pause();
          playButton.innerHTML = "Play";
        }
      });

    play.addEventListener("click", function c () { 
        if (video2.paused == true) { 
          video2.play(); 
          play.innerHTML = "Pause"; 
        } else {
          video2.pause();
          play.innerHTML = "Play"; 
        }
      });

HTML:

    <video width="900px" height="600px" id="Digital_Poster.mp4" />
      <source src="assets/video.mp4" type="video/mp4" id="video.mp4"/>
         Sorry, this browser does not support the 'video' tag.
    </video>
    <div id="video-controls">
      <button type="button" id="play-pause">Play</button>
    </div>

    <video width="900px" height="600px">
      <source src="assets/video2.mp4" type="video/mp4" id="video2.mp4"/>
         Sorry, this browser does not support the 'video' tag.
    </video>
    <div id="video-controls">
      <button type="button" id="play-pause2">Play</button>
    </div>

最佳答案

您应该调用.pause关于<video>元素,但是 id设置在 <source>那些。将其移至<video>标签应该让它工作:

    <video width="900px" height="600px" id="video.mp4">
      <source src="assets/video.mp4" type="video/mp4" />
         Sorry, this browser does not support the 'video' tag.
    </video>
    <div id="video-controls">
      <button type="button" id="play-pause">Play</button>
    </div>

    <video width="900px" height="600px" id="video2.mp4">
      <source src="assets/video2.mp4" type="video/mp4" />
         Sorry, this browser does not support the 'video' tag.
    </video>
    <div id="video-controls">
      <button type="button" id="play-pause2">Play</button>
    </div>

顺便说一下,我已经更正了 />>在第一行。另外,声明两个 ID 设置为 video-controls 的元素非法,请考虑使用 HTML classes (感谢@zer00ne 的指出)。

关于JavaScript 'x is not a function',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41916207/

相关文章:

javascript - 在HTML文件中嵌入CSS和JS

javascript - JSP:使用javascript提交表单

jquery - Bootstrap 模态表单适用于本地计算机,但不能实时运行

html - 如何使我的 DIV 与它所包含的文本大小相同

javascript - CSS/SCSS/JS : Dynamic height fixed header

javascript - 在循环中调用数组的索引导致错误

Javascript/Vue : set background-color on specific parts of string, 基于数组中的匹配值

javascript - 如何在 rivets.js 中打印数组

javascript - 如何使用 Modernizr 输入类型=日期时间?

html - CSS:输入字段和选择选项错误?