[英]How can I pass the id of an element in the addEventListener?
How can I get the id from many play buttons ? 如何从多个播放按钮获取ID?
I just get the last element when I alert the order. 当我提醒订单时,我只会得到最后一个元素。
I want do in the end something like: 我想最后做类似的事情:
videos[id].play();
instead of 代替
video.play();
window.addEventListener("load", function(event) { var videos = document.getElementsByTagName("video"); var btnsPlay = document.getElementsByClassName("btnPlay"); for (var i = 0; i < videos.length; i++) { var video = videos[i]; var btnPlay = btnsPlay[i]; // … find button objects and add listener … btnPlay.addEventListener("click", function (event) { var id = i; video.play(); alert(id); }); // … } });
<!DOCTYPE HTML> <html lang="de"> <head> <meta charset="utf-8"> </head> <body> <video width="20%" height="240" controls> <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm> <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg> <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4> <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp> Your browser does not support the video tag. </video> <div class ="controlbtn"> <button class="btnPlay">Play</button> </div> <video width="20%" height="240" controls> <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm> <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg> <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4> <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp> Your browser does not support the video tag. </video> <div class ="controlbtn"> <button class="btnPlay">Play</button> </div> <video width="20%" height="240" controls> <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm> <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg> <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4> <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp> Your browser does not support the video tag. </video> <div class ="controlbtn"> <button class="btnPlay">Play</button> </div> </body> </html>
Try changing 尝试改变
for (var i = 0; i < videos.length; i++)
To 至
for (let i = 0; i < videos.length; i++)
The reason this problem is happening is because when the function is being invoked the value of i
has already changed. 发生此问题的原因是因为在调用函数时,
i
的值已经更改。 You need to use let
to have it saved at the block scope level and not at the function scope level 您需要使用
let
将其保存在块作用域级别而不是功能作用域级别
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.