简体   繁体   中英

Load External Panel To Jquery Mobile Page

JQuery Mobile template which utilises a side panel. For simplicity I want to be able to load this panel from an 'external page' / seperate document so that it can be built once and used on many pages.

A bit of research has resulted in me getting the following code to load a string of html into a variable and then loading that variable into each page as the side panel:

/* Get the sidebar-panel as a var */
var side_var = '<div data-role="panel" id="left-panel" data-position="left" data-display="push"><h1>Panel</h1><p>stuff</p></div>';

/* Load the side-panel var to the DOM / page */
$(document).one('pagebeforecreate', function () {
  $.mobile.pageContainer.prepend( side_var );
  $("#left-panel").panel();
});

This works perfectly, however it still doesn't address the need to build the sidebar / panel as a separate html file.

A bit more work and I discovered this snippet to load a page into a variable:

$.get("http://www.somepage.com", function( side_var ) {}, 'html');

So in theory adding the two together should give me the desired result;

/* Get the sidebar-panel as a var */
$.get("mypage.html", function( side_var ) {}, 'html');


/* Load the side-panel var to the DOM / page */
$(document).one('pagebeforecreate', function () {
   $.mobile.pageContainer.prepend( side_var );
   $("#left-panel").panel();
});

However, all I get when running this is an eternally rotating AJAX loader.

What am I missing &/or doing wrong??


COMPLETE SOLUTION

Omar's solution below goes most of the way but needs one small but important addition to make the JQM elements display as expected. Here is the complete solution:

$(document).one("pagebeforecreate", function () {
  $.get('side-panel.html', function(data) { 
    //$(data).prependTo($.mobile.pageContainer); //or .prependTo("body");
    $.mobile.pageContainer.prepend(data);
    $("[data-role=panel]").panel().enhanceWithin(); // initialize panel
  }, "html");
});

Each element to be enhanced as a JQM element needs the data-theme adding to tell it which theme to use. Additionally in the JavaScript the initialised panel widget needs to .enhanceWithin() in order for the elements to be rendered with the desired style.

the $.get() function should be wrapped in pagebeforecreate event, to append contents directly once retrieved. Also, you need to initialize retrieved contents.

$(document).one("pagebeforecreate", function () {
  $.get('mypage.html', function(data){ 
    $(data).prependTo("body"); // or .prependTo($.mobile.pageContainer);
    $("[data-role=panel]").panel(); // initialize panel
  }, "html");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM