[英]Getting the href attribute of an image with Javascript
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属性或偏移属性:
e.src or e.offsetHeight
但是,当我使用时,它返回NULL:
return e.href;
那我怎样才能得到正确的href属性(http://www.abc.com)?
谢谢,
峰
href不是图像的属性,而是A元素的属性。
您可以使用图像的.parentNode
来.parentNode
它。 因为它是它的直接父母。
你可以得到的父节点img
,这是a
使用parentNode :
return e.parentNode.href;
href atrribute仅适用于a
和link
元素。 所以你只需要获取图像的父节点:
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
}
广告@米
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.