Load External Panel To Jquery Mobile Page

大兔子大兔子 提交于 2019-12-21 20:56:27

问题


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.


回答1:


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");
});


来源:https://stackoverflow.com/questions/22404657/load-external-panel-to-jquery-mobile-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!