Javascript 当 event.target 是 HTMLImageElement 时如何获取锚点的 href ?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29223502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get href of anchor when the event.target is HTMLImageElement?
提问by Aurelije Aure
I want to get the href of an anchor element when it is clicked. I am using the following javascript code:
我想在单击时获取锚元素的 href。我正在使用以下 javascript 代码:
document.addEventListener('click', function (event)
{
event = event || window.event;
var el = event.target || event.srcElement;
if (el instanceof HTMLAnchorElement)
{
console.log(el.getAttribute('href'));
}
}, true);
This works perfectly for an embedded anchor such as this:
这非常适用于嵌入式锚点,例如:
<div><p><a href='link'></a></p><div>
But it doesn't work when I am working with an anchor and an image:
但是当我使用锚点和图像时它不起作用:
<div><a href='link'><img></a></div>
The event.targetis returning the image instead of the anchor.
The javascript code can be amended with the following ifcase to get around this:
将event.target代替返回锚的形象。可以使用以下if情况修改 javascript 代码以解决此问题:
document.addEventListener('click', function (event)
{
event = event || window.event;
var el = event.target || event.srcElement;
if (el instanceof HTMLImageElement)
{
// Using parentNode to get the image element parent - the anchor element.
console.log(el.parentNode.getAttribute('href'));
}
else if (el instanceof HTMLAnchorElement)
{
console.log(el.getAttribute('href'));
}
}, true);
But this doesn't seem very elegant and I'm wondering if there is a better way.
但这似乎不是很优雅,我想知道是否有更好的方法。
!IMPORTANT!NOTE: Keep in mind, I have no access to an ID or class, or any other traditional identifier for that matter. All I know is that there will be an anchor clicked and I need to get its href. I don't even know where it will be, if it exists or will be created later.
!重要的!注意:请记住,我无法访问 ID 或类,或任何其他与此相关的传统标识符。我所知道的是会有一个锚点被点击,我需要得到它的href。我什至不知道它会在哪里,是否存在或稍后会创建。
EDIT: Please no jQuery or other javascript libraries.
编辑:请不要使用 jQuery 或其他 javascript 库。
回答by bvaughn
Rather than adding a global clickhandler, why not just target only anchor tags?
与其添加全局click处理程序,为什么不只针对锚标记?
var anchors = document.getElementsByTagName("a");
for (var i = 0, length = anchors.length; i < length; i++) {
var anchor = anchors[i];
anchor.addEventListener('click', function() {
// `this` refers to the anchor tag that's been clicked
console.log(this.getAttribute('href'));
}, true);
};
If you want to stick with the document-wide clickhandler then you could crawl upwards to determine if the thing clicked is-or-is-contained-within a link like so:
如果您想坚持使用文档范围的点击处理程序,那么您可以向上爬行以确定点击的内容是否包含在链接中,如下所示:
document.addEventListener('click', function(event) {
event = event || window.event;
var target = event.target || event.srcElement;
while (target) {
if (target instanceof HTMLAnchorElement) {
console.log(target.getAttribute('href'));
break;
}
target = target.parentNode;
}
}, true);
This way at least you'd avoid writing brittle code that has to account for all of the possible types of anchor-children and nested structure.
通过这种方式,至少您可以避免编写必须考虑所有可能类型的锚子节点和嵌套结构的脆弱代码。
回答by Roko C. Buljan
Instead of looping all anchors in the DOM, lookup from the event.targetelement.
Using JavaScript's .closest() MDN Docs(PS: polyfill for IE)
不是循环 DOM 中的所有锚点,而是从event.target元素中查找。
使用JavaScript 的 .closest() MDN Docs(PS: polyfill for IE)
document.addEventListener('click', function (event) {
event.preventDefault(); // Don't navigate!
var anchor = event.target.closest("a"); // Find closest Anchor (or self)
console.log( anchor.getAttribute('href')); // Log to test
}, true);
<a href="http://stackoverflow.com/a/29223576/383904">
<span>
<img src="//placehold.it/200x60?text=Click+me">
</span>
</a>
<a href="http://stackoverflow.com/a/29223576/383904">
Or click me
</a>
it basically works like jQuery's .closest() which does
它基本上像 jQuery 的 .closest() 那样工作
Closest or Self(Find closest parent... else - target me!)
最近或自己(找到最近的父母......否则 - 以我为目标!)
better depicted in the example above.
在上面的例子中更好地描述了。

