2013-04-01 178 views
0

我通過一個簡單的Google搜索找到了我的問題的答案,但是我遇到了一個小問題。通過Javascript查找圖像的src

到目前爲止,我在我的HTML頁面上有一個圖像,其ID爲newAvatar。我試圖通過它的ID來找到這個圖像,並將它的源代碼保存到一個變量中,然後最終放入一個XML文檔中以供以後使用。

當我將此源保存到一個變量中,或者爲了檢查目的而提醒它時,它顯示的是完整的源,這是不尋常的。例如,我正在我的WAMP的服務器上的站點,因此該變量保存爲:

http://localhost/uploads/newUploadedImage.jpg 

當在現實中,來源應該是簡單明瞭的,上傳/ newUploadedImage.jpg

圖像標籤是

<img src="uploads/newUploadedImage.jpg" width="60px" height="60px;" id="newAvatar"/> 

我檢查源的方式是

alert(document.getElementById('newAvatar').src); 

任何想法如何擺脫第一批垃圾?

所有幫助非常感謝!

+0

您可以在你的問題中的javascript和圖像標記? – greg84

+2

可能'this.getAttribute('src');'但沒有上下文(你的HTML和JavaScript)很難說或猜測。 –

+0

@DavidThomas - 添加了您要求的信息。謝謝。 – Fizzix

回答

0

通過使用@DavidThomas評論之前,我設法讓它工作。這是我改變了我的警惕:

alert(document.getElementById('newAvatar').getAttribute('src')); 
+0

檢查此作品在其他瀏覽器 - 我認爲老版本的IE可能有問題。可能需要使用像jQuery這樣的框架來確保更好的跨瀏覽器兼容性:'$('#newAvatar')。attr('src')' – greg84

0
var hostname = document.location.hostname; 
var url = 'http://' + hostname + '/'; 

var src = document.getElementById('newAvatar').getAttribute('src'); //'uploads/newUploadedImage.jpg' 
var image = src.split('/')[1]; 

console.log(url); 
console.log(image); 
0
<script 
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> 
</script> 

<img src="uploads/newUploadedImage.jpg" width="60px" height="60px;" 
    id="newAvatar"/> 

$(function() 
{ 
    alert($('#newAvatar').attr('src')); 
}); 
+0

jQuery標籤在哪裏? – epascarello

+0

@epascarello在警報調用周圍添加了ready事件處理程序。 –