event.preventDefault() is not working in IE 11 for custom events

烂漫一生 提交于 2019-12-02 01:55:25

问题


I have a polymer element which triggers a custom event synchronously and I want to know whether the event was cancelled using event.preventDefault(). Using event.defaultPrevented I can know the intended action. This works on all browsers(Chrome, Canary, Firefox, Opera) but on IE 11 (not worried about older browsers) its not working. I know I can set some property on my event and check for that back where I am triggering and handle but want to know if there is something else which I missed.

You can try out the code from http://jsbin.com/husamupi/1/edit


回答1:


I had the same problem and could solve it with the following hack:

var event = document.createEvent('CustomEvent');
event.initCustomEvent('custom', true, true, {});
event.preventDefault = function () {
    Object.defineProperty(this, "defaultPrevented", {get: function () {return true;}});
};
event.preventDefault();
event.defaultPrevented; // true



回答2:


It looks like IE 11 does not set defaultPrevented for "synthetic" events created by code.

Example JSbin: http://jsbin.com/wohafoyo/1/edit

No matter what I tried in terms of event creation and dispatching, I could not make a synthetic click event's preventDefault set defaultPrevented to true.

Perhaps Polymer could modify CustomElement.prototype.preventDefault to set defaultPrevented.



来源:https://stackoverflow.com/questions/23349191/event-preventdefault-is-not-working-in-ie-11-for-custom-events

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