简体   繁体   English

缩短代码 - 一个功能的多个输入/视频

[英]Shortening Code - Multiple inputs/video for one function

I want to shorten my code since the I am repeating the same function for each button and video, but I get lost when trying to understand how to make things run through the same function when clicked. 我想缩短我的代码,因为我正在为每个按钮和视频重复相同的功能,但是当我试图理解如何在点击时使相同的功能运行时,我迷路了。 Right now I am using onclick in HTML, but I would like for the code to use an eventListener as well and Javascript only. 现在我在HTML中使用onclick,但我希望代码也使用eventListener和Javascript。

I have tried using for loops for the button and video, but I will admit that I do not know what exactly it is that I'm doing. 我已经尝试使用for循环按钮和视频,但我承认我不知道我到底在做什么。

<script>

    // function for "stop"
    var vid1 = document.getElementById("video1");
        vid1.style.display = "none";
    var img1 = document.getElementById("button1");

        function vidToggle1() {
            img1.style.display = "none";
            vid1.style.display = "block";
            vid1.play();
        }
        vid1.onended = function() {
            vid1.style.display = "none";
            img1.style.display = "block";
        }

    // function for "more"
    var vid2 = document.getElementById("video2");
        vid2.style.display = "none";
    var img2 = document.getElementById("button2");

        function vidToggle2() {
            img2.style.display = "none";
            vid2.style.display = "block";
            vid2.play();
        }
        vid2.onended = function() {
            vid2.style.display = "none";
            img2.style.display = "block";
        }

</script>

Right now it the code does what I want, but I just want it shorter. 现在它的代码完成了我想要的,但我只想让它更短。 The code is supposed to display the input image and when clicked, it is supposed to play the video clip assigned to that input, then video is to go back to the initial image upon finished playing. 代码应该显示输入图像,当点击时,它应该播放分配给该输入的视频剪辑,然后视频将在完成播放后返回到初始图像。

You can just pass elements as function parameters. 您只需将元素作为函数参数传递即可。 For example: 例如:

function playVideo(vid, img) {
  img.style.display = "none";
  vid.style.display = "block";
  vid.play();

  vid.onended = function() {
    vid.style.display = "none";
    img.style.display = "block";
    vid.onended = undefined
  }
}


var vid1 = document.getElementById("video1");
vid1.style.display = "none";
var img1 = document.getElementById("button1");

var vid2 = document.getElementById("video2");
vid2.style.display = "none";
var img2 = document.getElementById("button2");

Then to play the first video you can call playVideo(vid1, img1) , and for the second playVideo(vid2, img2) . 然后播放第一个视频,您可以调用playVideo(vid1, img1) ,然后播放第二个playVideo(vid2, img2)

If you have any questions feel free to ask me in the comments. 如果您有任何问题,请随时在评论中询问我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM