我试图创建一个弹出窗口,当用户点击取消时将阻止用户转到结果页面。此代码适用于Chrome,Safari,Opera,Microsoft Edge和Internet Explorer 11,但不适用于Firefox。javascript stopPropagation/cancelBubble/preventDefault在Firefox中未启用
function leavingAlert(){
var check = confirm("You are about to leave the site! You may be going to a website that doesn't provide security. Do you wish to continue?");
if(check){
this.target="_blank"
return true;
}else{
event.cancelBubble = true;
return false;
}
}
//WORKING FOR ALL NON-IFRAME LINKS
var container = document.getElementById("wrapper");
var allATags = wrapper.getElementsByTagName("A");
for(var i = 0, len = allATags.length; i < len; i++){
var link = allATags[i];
//var pat = /^https?:\/\//i;
var pat = new RegExp("https://example.com");
var pat2 = new RegExp("javascript");
if(!pat.test(link.href)){
if(!pat2.test(link.href)){
link.onclick = leavingAlert;
}
}
}
我也用这些代替event.cancelBubble没有运气:
event.preventDefault ? event.preventDefault() : event.returnValue = false;
和
event.stopImmediatePropagation;
和
event.stopPropagation;
当我实现这个代码我目前无法使用jQuery所以在纯Javascript中的答案将是首选谢谢!
我只是读一些其他的问题,并来到了完全相同的结论,测试它,它的工作!只是将事件从函数括号中删除的超级愚蠢错误。 –