2013-02-12 878 views
0

我正在嘗試做一些類似於您離開的某些網站,它會顯示一個彈出窗口,顯示「您確定要離開此頁面」,並有兩個選項「取消」和「好」。「你確定要離開這個頁面嗎?」功能取消和確定

我該如何做到這一點,當你點擊「取消」它只會取消框,當他們點擊「確定」它會做'leaveChat();'功能並離開網站?

我試過使用onbeforeunload工作,但我不知道在功能部分。

感謝您的幫助!

+1

可能重複的[如何顯示「您確定要從此頁面導航?」當提交更改?](http://stackoverflow.com/questions/1119289/how-to-show-the-are-you-sure-you-want-to-navigate-away-from-this-page-when- ch) – 2015-02-19 08:56:45

回答

0

沒有辦法做到這一點。

您可以嘗試發送onunload中的AJAX請求,但我認爲這不會可靠地工作。

+1

我在很多網站上看到過它?:/ – user1783703 2013-02-12 23:03:58

+1

@ user1783703:您已經看過_什麼? 'onbeforeunload'不會告訴你用戶點擊了什麼。 – SLaks 2013-02-13 15:21:34

0

要彈出當用戶離開頁面,確認離開的消息,你只是做:

<script> 
    window.onbeforeunload = function(e) { 
     return 'Are you sure you want to leave this page? You will lose any unsaved data.'; 
    }; 
</script> 

要調用函數:

<script> 
    window.onbeforeunload = function(e) { 
     callSomeFunction(); 
     return null; 
    }; 
</script> 
+0

瀏覽器將處理用戶的點擊並決定離開頁面或繼續。沒有我知道的瀏覽器可以讓你控制頁面上的用戶,不讓他們離開。 – 2013-06-09 01:07:03

0

這裏是我的html

<!DOCTYPE HMTL> 
<meta charset="UTF-8"> 
<html> 
<head> 
<title>Home</title> 
<script type="text/javascript" src="script.js"></script> 
</head> 

<body onload="myFunction()"> 
    <h1 id="belong"> 
     Welcome To My Home 
    </h1> 
    <p> 
     <a id="replaceME" onclick="myFunction2(event)" href="https://www.ccis.edu">I am a student at Columbia College of Missouri.</a> 
    </p> 
</body> 

所以這是我在javaScript中做了類似的工作

var myGlobalNameHolder =""; 

function myFunction(){ 
var myString = prompt("Enter a name", "Name Goes Here"); 
    myGlobalNameHolder = myString; 
    if (myString != null) { 
     document.getElementById("replaceME").innerHTML = 
     "Hello " + myString + ". Welcome to my site"; 

     document.getElementById("belong").innerHTML = 
     "A place you belong"; 
    } 
} 

// create a function to pass our event too 
function myFunction2(event) { 
// variable to make our event short and sweet 
var x=window.onbeforeunload; 
// logic to make the confirm and alert boxes 
if (confirm("Are you sure you want to leave my page?") == true) { 
    x = alert("Thank you " + myGlobalNameHolder + " for visiting!"); 
} 
} 
相關問題