简体   繁体   English

如何获取通过在 forEach 中添加的单击处理程序单击的元素?

[英]How can I get the element that is clicked on with a click handler added in a forEach?

I need to detect element count number我需要检测元素计数

I have 10 poster elements and I have a forEach loop我有 10 个海报元素,我有一个forEach循环

I need the poster number that I clicked on, for example if I click on the seventh poster posternumber should be 7我需要我点击的海报编号,例如如果我点击第七张海报海报posternumber应该是7

    poster.forEach(p => {
            p.addEventListener('click',function(){
                videoTag.src = xResult[movieLanguageUrl][/*posternumber*/]; 
           });
    });

Check out the signatur of your forEach consumer function.查看您的forEach消费者 function 的签名。 The secound argument is the index.第二个参数是索引。

poster.forEach((p, idx) => {
    p.addEventListener('click',function(){
        videoTag.src = xResult[movieLanguageUrl][idx]; 
    });
});

Check out this link.看看这个链接。

Get the index value on the second parameter of the forEach function and it should work:获取forEach function 的第二个参数的索引值,它应该可以工作:

poster.forEach((p, index) => {
    p.addEventListener('click', () => {
        videoTag.src = xResult[movieLanguageUrl][index + 1]; 
   });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM