2016-06-30 64 views
0

我試圖創建一個彈出窗口,當用戶點擊取消時將阻止用戶轉到結果頁面。此代碼適用於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中的答案將是首選謝謝!

回答

0

使用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; 
    } 
} 
+0

我只是讀一些其他的問題,並來到了完全相同的結論,測試它,它的工作!只是將事件從函數括號中刪除的超級愚蠢錯誤。 –

0

這個問題似乎涉及到的getElementsByTagName(「A」),但在FF的實現是區分大小寫的

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

我想你在想'getElementsByTagNameNS'。 – Barmar