jQuery Mobile:按ID选择效果不佳

jQuery Mobile: selecting by ID doesn't work well

本文关键字:选择 ID Mobile jQuery      更新时间:2023-09-26

我有一个奇怪的问题与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')的值。长度*,它是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')来完成预期的结果?

    提前感谢!

    看起来您提交的表单导致第二个事件绑定到页面显示。如果您删除(或更改)表单上的Action会发生什么?同时,尝试:

    $(this).unbind('pageshow').bind('pageshow',function()...

    编辑

    我认为外部函数可能是多余的。为什么不把整个代码简化为:

    $('#mainPage').live('pageshow',function()
      {
        alert('Event triggered!');
        $(this).find('#contacts_list').html('<li>Reset list!</li>');
      }
    );