2012-10-04 101 views
0

您好我有我的手機應用兩個HTML頁面如下:window.onbeforeunload不是在第二頁的工作

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<title>jQuery Mobile: Demos and Documentation</title> 

<link rel="stylesheet" href="jquery.mobile/jquery.mobile-1.1.0.css" /> 
<link rel="stylesheet" href="docs/assets/css/jqm-docs.css" /> 
<link rel="stylesheet" href="docsdemos-style-override.css" /> 
<script type="text/javascript" src="jquery.mobile/jquery-1.7.2.min"></script> 
<script type="text/javascript" src="jquery.mobile/jquery.mobile-1.1.0.js"></script> 
<!-- Uncomment following line to access PhoneGap APIs (not necessary to use PhoneGap to package web app) --> 
<!-- <script type="text/javascript" charset="utf-8" src="cordova-1.6.1.js"></script>--> 


</head> 
<body> 
<div data-role="page" id="jqm-home" class="type-home"> 
<div data-role="content"> 

    <a href="example.html" data-role="button" id="myButton">Index</a>   

</div> 



</div> 
</body> 
</html> 

我example.html的是這樣的:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<title>jQuery Mobile: Demos and Documentation</title> 

<link rel="stylesheet" href="jquery.mobile/jquery.mobile-1.1.0.css" /> 
<link rel="stylesheet" href="docs/assets/css/jqm-docs.css" /> 
<link rel="stylesheet" href="docsdemos-style-override.css" /> 
<script type="text/javascript" src="jquery.mobile/jquery-1.7.2.min"></script> 
<script type="text/javascript" src="jquery.mobile/jquery.mobile-1.1.0.js"></script> 
<!-- Uncomment following line to access PhoneGap APIs (not necessary to use PhoneGap to package web app) --> 
<!-- <script type="text/javascript" charset="utf-8" src="cordova-1.6.1.js"></script>--> 


</head> 
<body> 
<div data-role="page" id="jqm-home" class="type-home"> 
<div data-role="content"> 

    <a href="example.html" data-role="button" id="myButton1">Test</a>   

</div> 

<script type="text/javascript"> 
    window.onbeforeunload = function(evt) { 
     console.log ("*****************"); 
    } 
</script> 




</div> 


</body> 
</html> 

現在就點擊猜想索引按鈕我轉到example.html頁面。點擊example.html中的後退按鈕,它會再次轉到index.html。一切正常,但它不打印console.log(「* ** * ****」);如果我再按一次index.html然後打印它,我想要的是當我在example.html上時,它應該在後退按鈕上單擊打印。

上面的代碼有什麼問題?爲什麼它的行爲如此呢?任何建議,將不勝感激提前。

回答

2

在jQuery Mobile的標準使用你的網站上的孔體驗中基本上停留在同一個頁面上。 「更改」頁面基本上將內容動態地添加到當前文檔,這意味着它不會觸發您的事件onbeforeunload事件。 然而,您可以使用jquery mobile events,哪一個取決於您想要採取的行動。最有可能你會看pagebeforehidepagehide

+0

謝謝使用pagebeforehide它完美的作品。 – PPD

0

你可以做的是將一個事件添加到後退按鈕。

如果你有一個按鈕:

<button id="backButton"> Go Back </button> 

你可以通過jQuery添加以下事件

$("#backButton).click(function(){ 
     console.log ("*****************"); 
    }); 

請記住,如果你點擊一個按鈕,後會發生和頁面會刷新。所以你應該在其他頁面的文檔準備好中添加日誌功能。

因此,如果exam​​ple.html的頁面加載後,你剛剛火這一事件

$(function(){ 
    //All code that starts when the page is fully loaded. 
    console.log ("*****************"); 
});