使用Javascript获取图像的href属性

发布于 2024-11-16 22:49:45 字数 527 浏览 7 评论 0原文

Javascript 新手,确实需要一些帮助!

现在我在 HTML 页面中有一个图像,如下所示:

<a class="p" href="http://www.abc.com"><img src="http://www.abc.com/logo.jpg" alt="" /></a>

并通过以下方式获取图像元素:

var e.document.elementFromPoint(x,y);

当我单击图像时,我可以通过以下方式成功获取 src 属性或 offset 属性:

e.src or e.offsetHeight

但是,当我使用时它返回 NULL:

return e.href;

那么如何我可以获得正确的 href 属性 (http://www.abc.com) 吗?

谢谢,

New to Javascript, really need some help!

Now I have an image in a HTML page, like this:

<a class="p" href="http://www.abc.com"><img src="http://www.abc.com/logo.jpg" alt="" /></a>

And get the image element by:

var e.document.elementFromPoint(x,y);

When I clicked on the image, I can get the src attribute or offset attributes successfully by:

e.src or e.offsetHeight

However, it returns NULL when I use:

return e.href;

So how can I get the correct href attribute (http://www.abc.com) ??

Thanks,

Peak

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

猫九 2024-11-23 22:49:45

href 不是图像的属性,而是 A 元素的属性。

您可以使用图像的 .parentNode 属性来访问它。因为它是它的直接父代。

The href is not a propery of the image but of the A element.

You can acces it by using the .parentNode propery of the image. as it is its direct parent.

如日中天 2024-11-23 22:49:45

您可以使用 父节点

return e.parentNode.href;

You can get the parent node of the img, which is the a using parentNode:

return e.parentNode.href;
暖伴 2024-11-23 22:49:45

href 属性仅适用于 alink 元素。所以你只需要获取图像的父节点:

var thea=e.parentNode;
if(thea.nodeName.toLowerCase()=="a"){ //If the tag is a hyperlink
    return thea.href;
}else{
    return ""; //Return an empty string if the image is not inside a hyperlink
}

Ad@m

The href atrribute is only available on a and link elements. So you just need to get the parent node of the image:

var thea=e.parentNode;
if(thea.nodeName.toLowerCase()=="a"){ //If the tag is a hyperlink
    return thea.href;
}else{
    return ""; //Return an empty string if the image is not inside a hyperlink
}

Ad@m

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文