0

How can I get the id from many play buttons ?

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>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Samy
  • 1,013
  • 3
  • 15
  • 25
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Sebastian Simon Oct 20 '16 at 23:28

1 Answers1

1

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. You need to use let to have it saved at the block scope level and not at the function scope level

qwertymk
  • 34,200
  • 28
  • 121
  • 184