How do I know which element was clicked?

[亡魂溺海] 提交于 2019-12-10 12:08:11

问题


I'm attempting the surprisingly difficult task of finding out which element was clicked. I have these functions from Head First AJAX:

function getActivatedObject(e) {
  var obj;
  if (!e) {
    obj = window.event.srcElement;
  } else if (e.srcElement) {
    obj = e.srcElement;
  } else {
    obj = e.target;
  }
  return obj;
}

function addEventHandler(obj, eventName, handler) {
  if (document.attachEvent) {
    obj.attachEvent("on" + eventName, handler);
  } else if (document.addEventListener) {
    obj.addEventListener(eventName, handler, false);
  }
}

And my code:

mainPane = document.getElementById("mainDiv");
contactPane = document.getElementById("contactDiv");
addEventHandler(mainPane, "click", openFunction);
addEventHandler(contactPane, "click", openFunction);

function openFunction(e) {
  var me = getActivatedObject(e);
  //Some other stuff
}

Unfortunately, the me variable sometimes refers to the div, but it sometimes refers to the image inside the div. Even though the image has no onclick function or any other kind of event! So how can I get the div that triggered the event?


回答1:


You're dealing with Event bubbling.

Basically, your click on a child element bubbles up through all of that child's parents; if those parents have a click handler bound to them, it will execute.

In pseudocode: you can see what element your current target is, and if it's not a DIV, you know that you need to look for that element's parent.

Using your example, it would look something like this (simplified a bit for your example; in reality, you'd need something much more robust):

function getActivatedObject(e) {
  var obj;
  if (!e) {
    obj = window.event.srcElement;
  } else if (e.srcElement) {
    obj = e.srcElement;
  } else {
    obj = e.target;
  }

  // Images are direct children of our DIV. If our source element was an img, we should
  // fetch its parent
  if(obj.tagName.toLowerCase() === "img"){
      obj = obj.parentNode;
  }

  return obj;
}

Note that this will work for your example only; in the real world, you would likely need to iterate back up the DOM tree, comparing parentNodes with the elements you are interested in until you've found what you're looking for.

Most JavaScript libraries abstract this away for you (jQuery, for example, sets a currentTarget property of all Events it dispatches that refers to the element you need, encapsulating all the traversal work for you). Makes it easier, but it's not too terrible a job to write that yourself and I'd argue against including the overhead of an entire JavaScript library if that's all you need to do. :-)

EDIT: Totally destroyed my formatting! D'oh!



来源:https://stackoverflow.com/questions/5833708/how-do-i-know-which-element-was-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!