开发者

Attaching properties to bubbled event object in Javascript

开发者 https://www.devze.com 2023-04-03 23:06 出处:网络
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.

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开发者_StackOverflow社区 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>


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.

0

精彩评论

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