我正在 jquery 移动应用程序中动态生成页面。他们展示。问题是,如果用户点击动态生成的页面上的重新加载按钮,将会返回到第一页。
这是一个例子。将以下文件另存为 t.html
<!DOCTYPE html>
<html>
<head>
<title>JQM latest - issue template</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/git/jquery.mobile-git.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/mobile/git/jquery.mobile-git.js"></script>
<script>$(document).ready(function(){
var newPage = '<div data-role="page" id="dynamic"><div data-role="header"><h1>Dynamic Page</h1></div><div class="ui-content"><ul><li>This page is dynamically generated.</li></ul></div></div>';
$.mobile.pageContainer.append(newPage);
});
</script>
</head>
<body>
<div data-role="page" id="homepage">
<div data-role="header">
<h1>Issue template</h1>
</div><!-- /header -->
<div class="ui-content">
<ul>
<li>We are on the Homepage</li>
<li>Go to <a href="#static">static</a></li>
<li>Go to <a href="#dynamic">dynamic</a></li>
</ul>
</div><!-- /content -->
</div><!-- /page -->
<div data-role="page" id="static">
<div data-role="header">
<h1>Static Page</h1>
</div><!-- /header -->
<div class="ui-content">
<ul>
<li>This page is in the index.html.</li>
</ul>
</div><!-- /content -->
</div><!-- /page -->
</body>
</html>
然后
- 在浏览器中加载 t.html
- 点击“static”,URL 现在将为 t.html#static,您将看到该页面
- 重新加载页面(点击浏览器的重新加载页面按钮),您仍然会看到#static
- 返回 t.html
- 点击“dynamic”,网址现在将为 t.html#dynamic,您将看到该页面
- 重新加载页面(浏览器重新加载按钮),您现在返回主页index.html,但网址仍然显示 t.html#dynamic
如何才能使当用户重新加载(第 6 步)动态页面时我们停留在该页面?
最佳答案
问题是,当您重新加载时,整个页面将从头开始创建,并且动态内容在该脚本运行之前并不存在。
你可以这样做:
$(document).on("pageinit", "#homepage", function(){
var newPage = '<div data-role="page" id="dynamic"><div data-role="header"><h1>Dynamic Page</h1></div><div class="ui-content"><ul><li>This page is dynamically generated.</li></ul></div></div>';
$.mobile.pageContainer.append(newPage);
if (window.location.hash == "#dynamic"){
setTimeout(GoToDynamicPage, 50);
}
});
function GoToDynamicPage(){
$.mobile.changePage("#dynamic");
}
在pageinit上,检查URL哈希,如果是动态页面的id,则使用changePage()转到那里。在重新加载动态页面之前,用户可能会立即看到主页。看来需要setTimeout来让jQM完成它的业务...
Here is a DEMO
在 fiddle 中,访问动态页面,然后右键单击并重新加载框架。
关于jquery - 重新加载动态生成的页面会导致返回到 jquery mobile 中的第一页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20704580/