在javascript中检索clicked元素的getAttribute [英] retrieve getAttribute of clicked element in javascript

查看:50
本文介绍了在javascript中检索clicked元素的getAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页上有很多图片.

i have number of images on my webpage.

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

我正在尝试使用下面的javascript获取点击图片的"src".

I am trying to get "src" of clicked images by using below javascript.

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

getImageName();

但是它给了错误this.getAttribute不起作用.

But its giving an error this.getAttribute is not function.

有什么主意吗?预先感谢

Any idea? Thanks in advance

推荐答案

由于 this 是点击处理程序中的文档对象,因此您可能需要检查点击是否发生在图像元素中

Because this is the document object in your click handler, so you may want to check whether the click has happened in an image element

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>

这篇关于在javascript中检索clicked元素的getAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆