2

I have an HTML document with multiple pages using jQuery Mobile's data-role="page". I am trying to call a panel on the second page but am receiving the error

cannot read property 'nodeType' of undefined

The error occurs when I try to transition to the second page. My basic page structure is as follows:

<body>
    <div data-role="page" id="page1">
        <a href="#page2"> Enter Page 2</a>
    </div>
    <div data-role="page" id="page2">
        <h3> tthis is page 2 </h3>
        <input type="button" id="myButton"> My Button </input>
        <div data-role="panel" id="myPanel">
            <p> Panel content </p>
        </div>
    </div>
</body>

The panel is being called through a function, but I still receive the same error when I comment out the function.

$(document).ready(function() {
    $('#myButton').on('click', function() {
        $('#myPanel').panel('open')
    })
})

The panel works if it is on the first page and if I define it on the first page and open it on the second, it still opens on the first. It is there when I hit the back button. I am using jQuery Mobile too is that has an effect on anything.

Why am I receiving this error? Is there a simple solution or do I need hack my way around this by creating the panel dynamically? Thanks.

4

1 回答 1

1

First off, never use .ready() in jQuery Mobile.

Important: Use $(document).bind('pageinit'), not $(document).ready()

The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate, and the DOM ready handler only executes for the first page. To execute code whenever a new page is loaded and created, you can bind to the pageinit event. This event is explained in detail at the bottom of this page.

Source: http://jquerymobile.com/demos/1.2.0/docs/api/events.html

Secondly, each page should have its' own panel with a different id, and the div containing the panel should be a direct child of data-role=page.

Panel markup/structure:

<div data-role="panel" id="id" data-position="left" data-display="push" data-theme="b">
  <!-- Contents -->
</div>

Opening a panel:

  1. Statically by using anchor/button:

    <a href="#panel_id" data-role="button" data-rel="panel">Open</a>
    
  2. Dynamically:

    $.mobile.activePage.find('[data-role=panel]').panel('open');
    // Or
    $('#panel_id').panel('open');
    

Closing a panel:

(in case data-dismissible is set to false)

  1. Statically by using anchor/button (Note: It should be placed inside Panel div):

    <a href="#panel_id" data-role="button" data-rel="close">Close</a>
    
  2. Dynamically:

    $.mobile.activePage.find('[data-role=panel]').panel('close');
    // Or
    $('#panel_id').panel('close');
    

Demo

于 2013-10-12T10:36:18.460 回答