2012-10-04 44 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 ("*****************"); 
});