如何在addEventListener中传递元素的id ?
How can I pass the id of an element in the addEventListener?
我如何从许多播放按钮获得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
将其保存在块作用域级别,而不是保存在函数作用域级别
相关文章:
- 选择不带选择器的元素,仅使用元素ID
- 从元素id中获取值,而不是从javascript中的名称中获取值
- 如何将第二个元素id注入到网站元素中
- 将 JavaScript 元素 ID 传递给 PHP 或 Form Variable
- 如何在 javascript 中将表单中的元素 id 值作为数组传递
- 用于指定元素 ID 的正确 JavaScript 语法是什么
- 如何从 jQuery 中的 ajax 函数中的类访问元素 ID
- JavaScript获取多个已知元素ID
- 使用ng repeat时元素ID重复
- 在使用onblur进行输入评估时,是否可以获得单击对象的元素id
- JQuery通过变量标识元素id:多个表行
- 当元素ID包含美元符号时,Javascript中的getElementByid.当ID包含美元符号时,
- 我得到未捕获的类型错误:无法读取属性'选项'即使定义了元素id,也为null
- 元素id未被接受为函数参数
- 使用jquery获取类元素id
- 如何在没有任何元素id的情况下检索表中的文本内容
- jquery按类确定元素id
- 获取元素ID并传递到函数中
- 使用jquery获取元素id
- JavaScript文档.getElementById(“id”)和元素id属性