javascript stopPropagation / cancelBubble / preventDefault无法在Firefox

时间:2016-06-30 21:15:35

标签: javascript firefox preventdefault stoppropagation

我试图制作一个弹出窗口,阻止用户点击取消时进入结果页面。此代码适用于Chrome,Safari,Opera,Microsoft Edge和Internet Explorer 11,但不适用于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中的答案会更受欢迎谢谢!

2 个答案:

答案 0 :(得分:1)

使用event作为全局变量不是标准的Javascript,并且它没有在Firefox中实现。它应该作为onclick处理程序的参数进行访问。

function leavingAlert(event){
    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;
    }
}

答案 1 :(得分:0)

该问题似乎与getElementsByTagName(“A”)有关,但在FF中,实现区分大小写

var allATags = wrapper.getElementsByTagName("a");