【发布时间】:2011-09-23 09:14:41
【问题描述】:
jQuery Mobile 有一个奇怪的问题... 下面是我的应用程序的 HTML 代码:
<!-- == START MAIN PAGE == -->
<div id="mainPage" data-role="page">
<div data-role="header" data-position="fixed">
<a href="#addContactPage"
data-transition="slidedown"
data-rel="dialog"
data-icon="plus"
data-iconpos="notext">Add a contact</a>
<h1>My repertory</h1>
</div>
<div data-role="content">
<p>
Welcome to your repertory!
</p>
<ul id="contacts_list"></ul>
</div>
<div data-role="footer" data-position="fixed">
<h1>Made with <em>jQuery Mobile</em></h1>
</div>
</div>
<!-- == END MAIN PAGE == -->
<!-- == START ADD CONTACT PAGE == -->
<div id="addContactPage" data-role="page">
<div data-role="header">
<h1>My repertory: add a contact</h1>
</div>
<div data-role="content">
<form id="addContactForm" action="#mainPage">
<div data-role="fieldcontain">
<input type="submit" value="Valid" />
</div>
</form>
</div>
</div>
当显示主页时,我想在 列表中设置一个项目:
//When the main page is created.
$('#mainPage').live('pagecreate',function()
{
//Just after the page is shown
$(this).bind('pageshow',function()
{
alert('Event triggered!');
$('#contacts_list').html('<li>Reset list!</li>');
});
});
所以,这是我的问题:当我启动应用程序时,此代码有效并且项目已设置。
如果我打开“添加联系人页面”(请注意这是一个对话框)并关闭它,这段代码也可以正常工作,并且完成了预期的结果。
但是如果我打开“添加联系人页面”然后提交它的表单,列表就会变成空的! alert() 已完成,因此触发了事件……但列表为空,就像未调用 html() 方法一样。 我试过提醒 *$('#contacts_list').lenght* 的值,它是 1,所以 jQuery 对象存在!
请注意,在提交表单期间我什么都没做:它的 submit 事件没有监听器。
如果我用这个替换代码:
//When the main page is created.
$('#mainPage').live('pagecreate',function()
{
//Just after the page is shown
$(this).bind('pageshow',function()
{
alert('Event triggered!');
$(this).find('#contacts_list').html('<li>Reset list!</li>');
});
});
那就好办了!
我真的不明白...
为什么使用 $(this).find('#contacts_list') 而不是使用 $('#contacts_list') 完成预期结果?
提前致谢!
【问题讨论】:
-
只是一个想法,如果对象存在可能需要刷新页面。试试这样的: $(this).find('#contacts_list').html('
- Reset list!
').trigger('create');或 $(this).find('#contacts_list').html('- 重置列表!
').page('refresh'); -
谢谢,但它不起作用:第一个代码没有任何变化,而第二个代码触发错误:在初始化之前无法调用页面上的方法;试图调用方法“刷新”。我提醒
$(this).find('#contacts_list').html('<li>Reset list!</li>');运行良好,是这段代码不起作用:$('#contacts_list').html('<li>Reset list!</li>');。这就像两个 jQuery 对象不引用同一个 DOM 元素!
标签: javascript jquery jquery-mobile