我试图制作一个弹出窗口,阻止用户点击取消时进入结果页面。此代码适用于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中的答案会更受欢迎谢谢!
答案 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");