如何在addEventListener中传递元素的id?

时间:2016-10-20 23:17:11

标签: javascript javascript-events

如何从许多播放按钮中获取ID?

当我提醒订单时,我才得到最后一个元素。

我最终想做的事情是:

videos[id].play();

而不是

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>

1 个答案:

答案 0 :(得分:1)

尝试更改

for (var i = 0; i < videos.length; i++)

for (let i = 0; i < videos.length; i++) 

发生此问题的原因是因为在调用函数时,i的值已经更改。您需要使用let将其保存在块范围级别而不是功能范围级别