问题
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
回答1:
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.
回答2:
You can get the parent node of the img
, which is the a
using parentNode:
return e.parentNode.href;
回答3:
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
来源:https://stackoverflow.com/questions/6452212/getting-the-href-attribute-of-an-image-with-javascript