Capturing clicks on all A tags using eventListener

别说谁变了你拦得住时间么 提交于 2019-12-13 14:51:26

问题


I'm trying to come up with a solution that will allow me to know whenever an "A" tag (or any other tag within an "A" tag) is clicked.

For example:

<a href="#">Link 1</a>
<a href="#"><span>Link 2</span></a>
<a href="#"><img src="#">Link 3</img></a>

So far I have this:

<script>
document.getElementsByTagName("BODY")[0].addEventListener('click', function(e) {
if(e.target && e.target.tagName == "A") {
console.log(e.target.text); }
}, false);
</script>

This is returning the text for link 1, but not for links 2 and 3. I also do not want to get any text if someone clicks on span or img elements that dont have an anchor tag.


回答1:


.target returns the element that was clicked on. In the case of link 2, this will always be the span tag; on a properly formed version of link 3 sometimes it would be the a tag, sometimes it would be the img tag depending where you click. In order to figure out if the .target is inside of a you need to climb up the DOM tree using parentNode until you reach an a node or the document itself, which has a .parentNode of null.

var getParentAnchor = function (element) {
  while (element !== null) {
    if (element.tagName.toUpperCase() === "A") {
      return element;
    }
    element = element.parentNode;
  }
  return null;
};

document.querySelector("body").addEventListener('click', function(e) {
  var anchor = getParentAnchor(e.target);
  if(anchor !== null) {
    console.log(anchor.textContent);
  }
}, false);

You should use .textContent.

It's easier to use querySelector to grab the body, unless you need to support IE7 or less.

It should also be noted that it is not valid to have a closing tag for an img tag, your HTML should look like this:

<a href="#">Link 1</a>
<a href="#"><span>Link 2</span></a>
<a href="#"><img src="example.jpg">Link 3</a>

jsFiddle

Update If you don't need to support IE (or Opera mini), the code can be simplified by using Element.closest method. You can completely get rid of the getParentAnchor and replace it with a single .closest call, shortening the code quite a bit:

document.querySelector("body").addEventListener('click', function(e) {
  var anchor = e.target.closest('a');
  if(anchor !== null) {
    console.log(anchor.textContent);
  }
}, false);

jsFiddle




回答2:


[].forEach.call(document.getElementsByTagName("a"),function(el){
  el.addEventListener("click",function(e){
    console.log(el.text);
  });
});

This code will just do the work for you. This will give attach click event to all the a tags. You can el.text to target text inside a.



来源:https://stackoverflow.com/questions/26879630/capturing-clicks-on-all-a-tags-using-eventlistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!