JQuery PreventDefault and IE8 clarification

ぐ巨炮叔叔 提交于 2019-12-01 05:12:07

问题


I have been trying to understand why sometimes IE8 doesn't like PreventDefault and why sometimes it seems to be OK (no errors). From what I have read, including here at SO is that events in jquery are normalised so preventDefault will always exist with a jQuery event. However regular javascript event bindings is when the following workaround is needed for ie8:

event.preventDefault ? event.preventDefault() : event.returnValue = false

Is this correct?

So if you are using jQuery .click .bind .on etc to handle an event then PreventDefault will not cause errors in IE8, such as:

$('a').on('click', function(e) {
    e.preventDefault();    //no need for e.preventDefault ? e.preventDefault() : e.returnValue = false as jquery event?
    //code
});

However if it is a regular Javascript event, such onclick then the workaround is needed?

Hope that makes sense.

Thanks


回答1:


Yes, your understanding sounds correct. Also, if you're using a "DOM0" event handler (e.g. someElement.onclick = function(e) { ... }), there is a simpler way to prevent the browser default behaviour that works in all browsers that support events: return false.

var someElement = document.getElementById("someElementId");
someElement.onclick = function(e) {
    // Do some stuff
    return false;
};

However, in this case, the event is not passed to the event handler in IE <= 8 and you have to get it from window.event instead.



来源:https://stackoverflow.com/questions/21033728/jquery-preventdefault-and-ie8-clarification

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