Attaching properties to bubbled event object in Javascript

时光总嘲笑我的痴心妄想 提交于 2020-01-01 16:53:29

问题


In Chrome/Firefox I can attach my custom properties to an event object in one handler and read them in a different handler for the same event even if the event handling is bubbled up.

I cannot do the same in IE. My custom property is lost while event is bubbled up. Do you know if there's any solution or workaround to this?

The following is an example of that problem:

<div id="div1">
<input type="button" value="Foo" id="button1">
</div>

<script>

function attach(el, event, fn) {
  if (el.addEventListener) {
    el.addEventListener(event, fn);
  } else if (el.attachEvent) {
    el.attachEvent('on'+event, fn);
  }

}

attach(document.getElementById("button1"), 'click', function (event) {
event.abc = "done";
return true;
});

attach(document.getElementById("div1"), 'click', function (event) {
alert(event.abc);
return true;
});

</script>

回答1:


According with my test you cannot add property to event object in IE (IE8 tested).

Try next code:

attach(document.getElementById("button1"), 'click', function (ev) {
  //ev=ev||event;
  //ev.abc = "done";
  // next lines show you why you cannot save properties in event object
  var xx1=event;
  var xx2=event;
  alert(xx1===xx2); // // showed *false* in IE8, but expected *true*

  return true;
});

I am not sure but maybe, when event object is requested, IE8 always return new object, that contains same properties/values as previous requested.



来源:https://stackoverflow.com/questions/7361869/attaching-properties-to-bubbled-event-object-in-javascript

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