目前,用户在打开应用程序时会看到登录页面。登录后,他们会进入主页面。我想阻止用户登录后返回登录页面,用户只需单击手机或网络浏览器上的后退按钮即可轻松完成。
以下方法可以防止我回到我想要的页面。例如,如果我将ID标识为#home
,则会阻止我返回主页。问题是这适用于我的应用程序中的所有页面,而不是我真正想要强制执行此操作的一个页面,这是我的登录页面。当我使用登录页面的ID时,没有任何反应,我可以通过单击后退按钮返回登录页面。请告诉我我做错了什么。
JS
// triggers when leaving any page
//this doesn't work cos I am using the id of my loginpage. Other page's ids works.
$(document).on('pagebeforechange', function (e, data) {
var to = data.toPage;
if (typeof to === 'string') {
var u = $.mobile.path.parseUrl(to);
to = u.hash || '#' + u.pathname.substring(1);
if (to === '#loginForm') { //will work if I use #benefits for example.
alert('Can not transition the page!');
$.mobile.changePage("#home", {
transition: "flip"
});
e.preventDefault();
e.stopPropagation();
// remove active status on a button, if transition was triggered with a button
$.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-shadow').css({
'box-shadow': '0 0 0 #3388CC'
});
}
}
});
登录页面的HTML
<div data-role="page" id="loginForm" data-theme="e" data-add-back-btn="false">
<header data-role="header">
<h1>Log In</h1>
</header>
<form id="form1" name="form1" method="GET" action="http://example.com">
<label for="id">Username </label>
<input type="text" name="id" id="id" />
<label for="password">Password </label>
<input type="password" name="password" id="password" />
<input type="hidden" name="rank" id="rank" value="123">
<input type="submit" name="submit" value="Login"/>
</form>
</div>
HTML for Benefits页面
<div data-role="page" id="benefits" data-theme="e">
<header data-role="header">
<h1>Benefits</h1>
</header>
<article data-role="content" >
<div data-role="collapsible-set" id="benefitsList">
<!--will fill up with info from database-->
</div>
</article>
</div>
编辑:
$(document).on('pagebeforechange', function (e, data) {
var to = $.mobile.path.parseUrl(data.toPage);
if (typeof to === 'object') {
var u = to.href;
if (u === $.mobile.navigate.history.stack[0].url) {
alert('You are logged in!');
var current = $.mobile.pageContainer.pagecontainer("getActivePage");
$.mobile.pageContainer.pagecontainer("change", current);
}
}
});
答案 0 :(得分:2)
上面的代码在除第一个页面加载之外的所有页面上工作的问题是因为 - 默认情况下 - jQM不会更改第一页的URL中的哈希值。上面的代码检查是否从URL检索hash
,因为第一页没有hash
,它返回false
,因此不会阻止用户返回“登录页面”
下面的代码检查网址并将其与加载的第一页的.url
进行比较。 .url
存储在$.mobile.navigate.history.stack
中,并且它有0
索引,因为它是第一页。
$(document).on('pagebeforechange', function (e, data) {
var to = $.mobile.path.parseUrl(data.toPage);
if (typeof to === 'object') {
var u = to.href;
if (u === $.mobile.navigate.history.stack[0].url) {
alert('You are logged in!');
var current = "#" + $.mobile.pageContainer.pagecontainer("getActivePage")[0].id;
window.location.hash += current;
return false; /* this will stop page change process */
}
}
});