2015-07-13 118 views
0

我的网页上有多个图像。检索javascript中单击元素的getAttribute

<img id="a" src="1.jpg"> 
<br> 
<img id="b" src="2.jpg"> 

我想通过使用下面的JavaScript获取点击图像的“src”。

var getImageName = function(){ 
    document.onclick = function(){ 
     var image = this.getAttribute("src"); 
     alert(image); 
     }} 

getImageName(); 

但是它给出的错误this.getAttribute不是函数。

有什么想法? 在此先感谢

回答

5

因为this在你单击处理文档对象,所以你可能要检查的点击是否发生在图像元素

var getImageName = function() { 
 
    document.onclick = function(e) { 
 
    if (e.target.tagName == 'IMG') { 
 
     var image = e.target.getAttribute("src"); 
 
     alert(image); 
 
    } 
 
    } 
 
} 
 

 
getImageName()
<img id="a" src="//placehold.it/64X64&text=1" /> 
 
<br> 
 
<img id="a" src="//placehold.it/64X64&text=2" /> 
 
<br>

+0

能否请您详细说明这个和目标有什么不同? – Nomad

+0

@Nomad,因为您已将处理程序绑定到文档对象,hadnler中的this将引用文档对象 –

+0

@Nomad [Event.target](https://developer.mozilla.org/en-US/docs/Web/API/Event/target)将引用调度该事件的元素,因此它将是'image'元素 –