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

How can I pass the id of an element in the addEventListener?

本文关键字:元素 id addEventListener      更新时间:2023-09-26

我如何从许多播放按钮获得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>

尝试更改

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

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

这个问题发生的原因是因为当函数被调用时,i的值已经改变了。您需要使用let将其保存在块作用域级别,而不是保存在函数作用域级别