问题描述:

I need to translate this jquery to vanilla js:

$(document).on('click', 'a', function(){

//do something

});

I've tried with

document.addEventListener('click', function(e) {

if(e.target.tagName === 'A')

{

//do something

}

});

But it's not working if the element clicked is a child of an a, for example

<a href="...">

<!-- if I click on the image, e.target.tagName === 'IMG' -->

<img src="img.jpg">

</a>

I can't use document.getElementsByTagName('a'), because It should work even with those created dynamically.

Also, I'd need to access the href property of the a.

What is the simplest way to do this?

网友答案:

In modern browsers you can use Element.closest() - Not supported in IE

document.addEventListener('click', function(e) {
  e.preventDefault();
  if (Element.prototype.closest) {
    if (e.target.closest('a')) {
      console.log('found')
    }
  } else {
    //else the long way
    var el = e.target;
    while (el && el.tagName != 'A') {
      el = el.parentNode;
    }
    if (el) {
      console.log('found')
    }
  }
});
<a href="...">
  This and image
  <img src="img.jpg">
</a>
Not here
网友答案:

Take the DOM for a Walk

You have a anchor tag that contains an image and you want catch click events.

The currentTarget property (as suggested in a comment) is not useful since the handler is attached to document, i.e., currentTarget = document.

The solution is to catch clicks on the image and then walk up the DOM tree to check if the parent element is an anchor tag.

The code below illustrates how you might accomplish this check using a while loop. It also displays target, currentTarget, and parentElement. As you can see, clicking on the text within the link produces different output than clicking on the image.

Run the snippet to try

document.addEventListener('click', function(e) {
  var t = e.target;
  while (t) {
    if (t.tagName === 'A') {

      // do something ...

      debug.innerHTML += (
        'target = ' + e.target +
        '\ncurrentTarget = ' + e.currentTarget +
        '\nparentElement.tagName = ' + t.tagName + '\n'
      );

      break;
    }
    t = t.parentElement;
  }


});


// dynamically add link with image
var a = document.createElement('A');
a.href = 'javascript:void(0)';
a.innerHTML = 'Click Me!<br><img src="http://lorempixel.com/100/50">';
document.getElementById('content').appendChild(a);
img {width:100px;height:50px;background-color:aliceblue;}
<span id="content"></span>
<xmp id="debug"></xmp>
相关阅读:
Top