2011-06-23 65 views
5

剛接觸Javascript,真的需要一些幫助!使用Javascript獲取圖像的href屬性

現在我有一個圖像中的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)?

謝謝,

峯值

回答

4

中的HREF不是圖像而是A元素的屬性格式。

您可以通過使用.parentNode圖像來訪問它。因爲它是它的直接父母。

3

你可以得到img的父節點,這是一個使用parentNodea

return e.parentNode.href; 
+0

偉大的!它的工作原理,謝謝。 – PeakJi

1

的HREF atrribute只在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 
} 

廣告@米