2013-04-01 180 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事件处理程序。 –