我在 jQueryMobile 中动态生成页面,但我不明白为什么新生成的页面没有更新到最新版本。
这是用例:
页面 A 包含“a”元素的列表。当我单击其中一个时,应用程序会重定向到动态生成的新页面。然后我返回到页面 A。我单击另一个“a”元素,但从现在开始,应用程序将始终重定向到动态生成的第一个页面。
请看看这个 fiddle :
http://fiddle.jshell.net/cqUrD/
这是我的代码:
HTML
<div data-role="page" id="home">
<div data-role="header" data-position="fixed">
<h1>static page</h1>
</div>
<div data-role="content"> <a href="#" data-role="button" id="createfirst">Create new page</a>
<div data-role="content"> <a href="#" data-role="button" id="createanother">Create another new page</a>
</div>
<div data-role="footer" data-position="fixed">
<h1>footer</h1>
</div>
</div>
jQueryMobile:
$(document).on('click','a',function() {
nameId = $(this).attr('id');
page = '<div data-role="page" id="page" data-theme="e"><div data- role="header"><a data-role="button" href="#" data-rel="back" data-icon="back" data-iconpos="notext">back</a><h1>Dynamic page</h1></div><div data-role="content"> Last id was: '+nameId+'</div><div data-role="footer" data-position="fixed"><h1>footer</h1></div></div>';
//alert(nameId); this prints the right value
$.mobile.activePage.after(page);
$.mobile.changePage('#page', {
transition: 'flip'
});
});
如何解决这个问题?我需要始终显示新页面的更新版本。
提前致谢!
最佳答案
工作示例:http://jsfiddle.net/Gajotres/Xfh8p/
在创建新页面之前,必须删除之前的页面。在这种情况下,DOM
填充了新页面,但第一个页面仍然存在,并且因为它们都具有相同的名称,所以第一个页面具有优先级。
此外,在绑定(bind)点击事件时不要仅将其绑定(bind)到标签,这也是一个问题。每次按下返回按钮时,都会在 DOM
中创建另一个页面。
总而言之,这将起作用:
$(document).on('pageinit', '#home', function(){
$(document).on('click','#createfirst, #createanother',function() {
nameId = $(this).attr('id');
alert(nameId);
page = '<div data-role="page" id="page" data-theme="e"><div data- role="header"><a data-role="button" href="#" data-rel="back" data-icon="back" data-iconpos="notext">back</a><h1>Dynamic page</h1></div><div data-role="content">'+nameId+'</div><div data-role="footer" data-position="fixed"><h1>footer</h1></div></div>';
$.mobile.activePage.after(page);
$.mobile.changePage('#page', {
transition: 'flip'
});
});
});
$(document).on('pagehide', '#page', function(){
$(this).remove();
});
在这种情况下,pagehide
事件已绑定(bind)到动态创建的页面。因为它绑定(bind)到文档对象,所以当页面被删除时它仍然存在。它告诉 jQuery Mobile
在转换过程中删除页面 #page。
如您所见,我使用 jQuery Mobile 页面事件来触发页面删除。如果您想了解有关此主题的更多信息,请查看我的其他 ARTICLE (我的个人博客)或找到它HERE 。
关于javascript - jQueryMobile - 为什么新的动态生成的页面没有更新到最新版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17226072/