开发者

How do I know which element was clicked?

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?


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜