[英]Adding an eventListener to multiple elements while utilizing an attribute from a child element
In my HTML I have this tag hierarchy repeated a bunch: 在我的HTML中,我将此标记层次结构重复了一堆:
<figure>
<div class="proj-photo">
<img>
<div></div>
<a></a>
</div>
<figcaption></figcaption>
</figure>
When I am on a non-touch screen I have a hover effect which displays the a tag as a button to launch a link. 当我在非触摸屏上我有其中显示了一个标签为一个按钮启动一个链接悬停效果。
On a touch screen I want to add an eventListener to the entire figure which launches the href of its embedded a tag when its pressed. 在触摸屏我想一个事件监听添加到其按下时推出其嵌入式标签的href整个身影。
This is what I've written, but it doesn't work: 这是我写的,但是不起作用:
const isTouchScreen = window.matchMedia( "(hover: none)" )
if (isTouchScreen.matches){
console.log("Touch screen in use")
const figures = document.querySelectorAll("figure")
const projLinks = document.querySelectorAll("figure > div > a")
var i = 0
function clickHandler(i){
window.open(projLinks[i], '_blank')
}
function assignListeners(i){
figures[i].addEventListener('click', clickHandler(i))
}
for (i in figures) {
assignListeners(i)
}
}
There are a few things that needs to be fixed in your code: 您的代码中需要修复一些问题:
Your loop pass the element, not its index, so it needs to look like this 您的循环传递的是元素,而不是其索引,因此它需要看起来像这样
for( var i = 0; i < figures.length; i++) { assignListeners(i) }
To have access to its position index you could store it in a custom attribute. 要访问其位置索引,可以将其存储在自定义属性中。 Note, I also removed the
(i)
from clickHandler
, or else it will fire when add the handler. 注意,我还从
clickHandler
删除了(i)
,否则添加处理程序时它将触发。
function assignListeners(i){ figures[i].setAttribute('data-id', i); figures[i].addEventListener('click', clickHandler); }
Then when clicked at, you can use the custom attribute to do something with 然后,当您单击时,可以使用custom属性对
function clickHandler(e){ alert(this.dataset.id) }
Stack snippet (disabled the touch detection for this sample to work) 堆栈摘要(已禁用触摸检测以使该示例正常工作)
//const isTouchScreen = window.matchMedia( "(hover: none)" ) //if (isTouchScreen.matches){ //console.log("Touch screen in use") const figures = document.querySelectorAll("figure") const projLinks = document.querySelectorAll("figure > div > a") var i = 0 function clickHandler(e){ alert(this.dataset.id) } function assignListeners(i){ figures[i].setAttribute('data-id', i); figures[i].addEventListener('click', clickHandler); } for( var i = 0; i < figures.length; i++) { assignListeners(i) } //}
<figure> <div class="proj-photo"> <img src="http://placehold.it/100"> <div></div> <a href="#">Link</a> </div> <figcaption></figcaption> </figure> <figure> <div class="proj-photo"> <img src="http://placehold.it/100"> <div></div> <a href="#">Link</a> </div> <figcaption></figcaption> </figure>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.