e.target引用的图片不是<a>

时间:2016-12-26 16:29:54

标签: javascript

I have code that looks like this:

<a href="someline">
<img src="img.jpg"/>
</a>

I have code all over my page, to get the links, and get their href like this:

e.target.href

The problem is, when clicking the link that contains the image, then e.target is the image itself not the anchor tag. I tried setting the href on the image as a bad solution, but e.target.href is undefined on the image.

How do I solve it so that e.target will reference the <a> not the image.

2 个答案:

答案 0 :(得分:2)

我们确实需要查看更多代码,但如果处理程序附加到a元素,请使用e.currentTarget(或this)而不是{ {1}}。

如果没有(例如,您正在使用事件委托或其他内容),请检查e.target并使用tagName,直至找到parentNode

a

答案 1 :(得分:1)

您可以将onclick事件附加到image并使用Node.parentElement获取代码中的a父元素:

&#13;
&#13;
document.getElementById('myImage').onclick = function(e) {
  e.preventDefault();
  
  console.log(e.target.parentElement.href);
};
&#13;
<a href="someline">
  <img id="myImage" src="https://placehold.it/350x150"/>
</a>
&#13;
&#13;
&#13;