如何在JavaScript中获取单击的div元素的ID? [英] How do you get an ID of a clicked div element in JavaScript?

查看:63
本文介绍了如何在JavaScript中获取单击的div元素的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的问题是如何获取刚刚点击的元素的ID? (JavaScript)

So my question is how to get an ID of an element that has just been clicked? (JavaScript)

感谢您的回答!

推荐答案

你可以使用目标元素(在IE以外的所有浏览器中)和srcElement(在IE中)来检索被点击的元素:

You can use the target element (in all browsers except IE) and srcElement (in IE) in order to retrieve the clicked element:

function click(e) {
  // In Internet Explorer you should use the global variable `event`  
  e = e || event; 

  // In Internet Explorer you need `srcElement`
  var target = e.target || e.srcElement;

  var id = target.id;
}

但请注意事件冒泡。 目标可能不是您期望的元素。

However be aware of event bubbling. The target may not be the element you expect.

这篇关于如何在JavaScript中获取单击的div元素的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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