简体   繁体   English

事件委派从列表中获取点击属性

[英]Event delegation get attribute on click from list

I tried getting href attribute with event.target.getAttribute('href') but due to event delegation. 我尝试使用event.target.getAttribute('href')获取href属性,但由于事件委派。 event.target seems to be set to either span or i . event.target似乎设置为spani

<a href="#gallery">
  <i class="fa fa-camera"></i>
  <span class="menu-text">Gallery</span>
</a>
<a href="#download">
  <i class="fa fa-cloud-download"></i>
  <span class="menu-text">Download</span>
</a>   


//script
 for (var i = 0; i < links.length; i++) {
    links[i].addEventListener('click', openMenu);
}
function openMenu(event) {
    event.preventDefault();
    var clickedMenu = event.target.getAttribute('href');
    document.querySelector(clickedMenu).style.display = 'block';
}

Kindly provide some guidance. 请提供一些指导。 I do not need a jquery solution. 我不需要jquery解决方案。

Since you have children for the links, event.target may refer to those elements if the click had happened on them. 由于您有链接的子项, event.target可能会引用这些元素,如果它们发生了点击。

You can use this inside the handler to refer to the link element, another option is to use event.currentTarget 您可以在处理程序内部使用this来引用link元素,另一个选项是使用event.currentTarget

 var links = document.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { links[i].addEventListener('click', openMenu); } function openMenu(event) { event.preventDefault(); var clickedMenu = this.getAttribute('href'); result.innerHTML = clickedMenu + ' or ' + event.currentTarget.getAttribute('href'); document.querySelector(clickedMenu).style.display = 'block'; } 
 .hidden { display: none; } 
 <a href="#gallery"> <i class="fa fa-camera"></i> <span class="menu-text">Gallery</span> </a> <a href="#download"> <i class="fa fa-cloud-download"></i> <span class="menu-text">Download</span> </a> <div id="result"></div> <div id="gallery" class="hidden">gallery</div> <div id="download" class="hidden">download</div> 

Why do not you try 你为什么不试试

event.currentTarget.getAttribute("href") event.currentTarget.getAttribute(的 “href”)

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

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