离开现场时使用确认方法

时间:2013-01-28 21:40:10

标签: javascript html hyperlink confirm

我想在点击外部链接时弹出确认消息。虽然它不想解决。当我点击外部链接时,我没有得到确认弹出窗口。任何解决方案?

Javascript代码

function warning(){
    var warning = confirm('Do you want to leave');
    if(!warning){
    alert("Staying on site");
    return false;
    } else {
        alert("Leaving site");
    return true;
    }
}

function init() {
    var warn = document.getElementsByTagName("ul");
    for(i=0; i<warn.length; i++)
        if(warn[i].className == "meny"){
            var link = document.getElementsByTagName("li");
    }
    for(i=0; i<link.length; i++){
        var links = document.getElementsByTagName("a");
        if(links[i].className == "external"){
            links.onclick = warning;
        }
    }
}

Html代码:

<ul class="meny"">
<li><a class="external" href="https://www.mah.se">Mah</a></li>
<li><a class="external" href="https://www.google.se/">Google</a></li>
<li><a class="external" href="http://www.facebook.com/">Facebook</a></li>
<li><a class="external" href="http://www.youtube.com/">Youtube</a></li>
<li><a href="#">Digitalt</a></li>
<li><a href="#">Kultur</a></li>
<li><a href="#">Nöje</a></li>
<li><a href="#">Sport</a></li>
<li><a href="#">Familj</a></li>
<li><a href="#">Resor</a></li>
<li><a href="#">Inrikes</a></li>
<li><a href="#">Utrikes</a></li>
<li><a href="#">Jobb</a></li>
</ul>

2 个答案:

答案 0 :(得分:3)

此行为只能通过处理onbeforeunload事件来完成。您的处理程序应返回一个字符串,该字符串是向用户显示的消息。一个简单的例子:

window.onbeforeunload = function () {
    return 'are you sure you want to leave?';  
};

http://jsfiddle.net/rHkfM/

答案 1 :(得分:0)

我建议您稍微修改一下代码:

function init() {
    var warn = document.getElementsByTagName("ul");
    for(i=0; i<warn.length; i++)
        if(warn[i].className == "meny"){
            var link = document.getElementsByTagName("li");
    }
    var links = document.getElementsByTagName("a");
    for(i=0; i<link.length; i++){
        if(links[i].className == "external"){
            links.external = true;
        }
    }
}

然后添加:

window.onbeforeunload = function (event) {
    if (event.srcElement.external)
        return 'are you sure you want to leave?';  
};

请注意,这一行:

    var links = document.getElementsByTagName("a");

必须在循环之外。