如何在JavaScript中获取单击的div元素的ID?

如何在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.