我試圖創建一個彈出窗口,當用戶點擊取消時將阻止用戶轉到結果頁面。此代碼適用於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中的答案將是首選謝謝!
我只是讀一些其他的問題,並來到了完全相同的結論,測試它,它的工作!只是將事件從函數括號中刪除的超級愚蠢錯誤。 –