阻止windows.onbeforeunload
被IE中的javascript:href
链接触发,可以通过以下方法实现:
event.preventDefault()
方法在windows.onbeforeunload
事件处理程序中,使用event.preventDefault()
方法可以阻止事件的默认行为,从而避免javascript:href
链接触发windows.onbeforeunload
事件。
示例代码:
window.onbeforeunload = function(event) {
event.preventDefault();
event.returnValue = '';
};
event.stopPropagation()
方法在windows.onbeforeunload
事件处理程序中,使用event.stopPropagation()
方法可以阻止事件冒泡,从而避免javascript:href
链接触发windows.onbeforeunload
事件。
示例代码:
window.onbeforeunload = function(event) {
event.stopPropagation();
event.returnValue = '';
};
addEventListener
方法使用addEventListener
方法为windows.onbeforeunload
事件添加处理程序,并在处理程序中使用event.preventDefault()
或event.stopPropagation()
方法阻止事件的默认行为或冒泡。
示例代码:
window.addEventListener('beforeunload', function(event) {
event.preventDefault();
event.returnValue = '';
});
javascript:void(0)
替换javascript:href
链接在HTML中,使用javascript:void(0)
替换javascript:href
链接可以避免触发windows.onbeforeunload
事件。
示例代码:
<a href="javascript:void(0)">链接</a>
return false
替换javascript:href
链接在HTML中,使用return false
替换javascript:href
链接可以避免触发windows.onbeforeunload
事件。
示例代码:
<a href="javascript:void(0)" onclick="return false">链接</a>
通过以上方法,可以有效地阻止windows.onbeforeunload
被IE中的javascript:href
链接触发。
领取专属 10元无门槛券
手把手带您无忧上云