简体   繁体   中英

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? (It is auto-playing the video instead and the eventListener no longer works)

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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