问题
I want a confirm message to popup when clicking on an external link. Though it doesnt want to work out. I dont get the confirm popup when i click on an external link. Any solutions ?
Javascript code
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 code:
<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>
回答1:
This behavior can only be accomplished by handling the onbeforeunload
event. Your handler should return a string, which is the message that appears to the user. A simple example:
window.onbeforeunload = function () {
return 'are you sure you want to leave?';
};
http://jsfiddle.net/rHkfM/
回答2:
May I suggest to slightly modify your code:
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;
}
}
}
then add:
window.onbeforeunload = function (event) {
if (event.srcElement.external)
return 'are you sure you want to leave?';
};
Please pay attention, this line:
var links = document.getElementsByTagName("a");
must be outside the loop.
来源:https://stackoverflow.com/questions/14571731/using-the-confirm-method-when-leaving-site