简体   繁体   English

如何在javascript中将DOM元素作为参数传递?

[英]How can I pass a DOM element as a parameter in javascript?

I want to pass the myVideo element as a parameter in the play() function, but it does not work? 我想将myVideo元素作为参数传递给play()函数,但是它不起作用? (It is auto-playing the video instead and the eventListener no longer works) (它会自动播放视频,而eventListener不再起作用)

If I use the element directly in the function it work. 如果我直接在函数中使用元素,它将起作用。 So I am wondering is it ever possible to pass a DOM element as a parameter and if so is it ever used 所以我想知道是否有可能将DOM元素作为参数传递,如果可以,是否曾经使用过

Here is the code below: 这是下面的代码:

// Get our elements
const myVideo = document.querySelector(".player__video");
const playButton = document.querySelector(".player__button");
console.log(myVideo);

function play(video) {

    if (video.paused) {
        video.play();
    } else {
        video.pause();
    }
}

playButton.addEventListener('click', play(myVideo))
playButton.addEventListener('click', function(){play(myVideo)})

You need to pass a function but instead you are passing the result of a function. 您需要传递一个函数,但是您传递的是函数的结果。 JavaScript has first class functions, so get used to this thing. JavaScript具有一流的功能,因此请习惯一下。

const myVideo = document.querySelector(".player__video");
const playButton = document.querySelector(".player__button");
console.log(myVideo);

function play(video) {

    if (video.paused) {
        video.play();
    } else {
        video.pause();
    }
}

playButton.addEventListener('click', () => play(myVideo) );

will works. 将有效。 addEventListener requires the second parameter as a Function, but you passed a value as undefined. addEventListener要求第二个参数作为Function,但是您传递了一个未定义的值。

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

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