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.
答案 0 :(得分:2)
我们确实需要查看更多代码,但如果处理程序附加到a
元素,请使用e.currentTarget
(或this
)而不是{ {1}}。
如果没有(例如,您正在使用事件委托或其他内容),请检查e.target
并使用tagName
,直至找到parentNode
:
a
答案 1 :(得分:1)
您可以将onclick
事件附加到image
并使用Node.parentElement获取代码中的a
父元素:
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;