我的网页上有很多图片.
<img id="a" src="1.jpg">
<br>
<img id="b" src="2.jpg">
Run Code Online (Sandbox Code Playgroud)
我试图通过使用下面的javascript获得点击图像的"src".
var getImageName = function(){
document.onclick = function(){
var image = this.getAttribute("src");
alert(image);
}}
getImageName();
Run Code Online (Sandbox Code Playgroud)
但是它给出了一个错误this.getAttribute不是函数.
任何的想法?提前致谢
因为this是单击处理程序中的文档对象,所以您可能想要检查单击是否发生在图像元素中
var getImageName = function() {
document.onclick = function(e) {
if (e.target.tagName == 'IMG') {
var image = e.target.getAttribute("src");
alert(image);
}
}
}
getImageName()Run Code Online (Sandbox Code Playgroud)
<img id="a" src="//placehold.it/64X64&text=1" />
<br>
<img id="a" src="//placehold.it/64X64&text=2" />
<br>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5798 次 |
| 最近记录: |