jquery mobile header repeat across pages

2019-07-15 17:09发布

问题:

I'm setting up a multi-page jquery mobile page based on the provided template: http://jquerymobile.com/demos/1.1.1/docs/pages/multipage-template.html

How can I get the header/footer to repeat on all the pages without duplicating it in the page content.

Is there a jquery script for this or do I have to use some kind of php include file?

Thanks in advance!

回答1:

You can use JS (jQuery) to make a template and append it to each data-role="page" element as it's being created.

//create template, notice the "{TITLE}" place-holder for dynamically adding titles
var myHeaderHTML = '<div data-role="header" data-id="my-header" data-position="fixed"><h1>{TITLE}</h1></div>';

//create delegated event handler for the "pagecreate" event for all pseudo-pages
$(document).on('pagecreate', '[data-role="page"]', function () {

    //get the title of this page, if none is given then use a generic title
    var title = $(this).data('title') || 'Some Generic Title';

    //add the header to this pseudo-page
    $(this).append(myHeaderHTML.replace('{TITLE}', title));
});​

Here is a demo: http://jsfiddle.net/vmMVj/

This will append a fixed header to every page as it is being created. I added support for passing a unique title by adding a data-title="Some Title" attribute to the data-role="page" element.

Note that I chose the pagecreate event because it occurs when the pseudo-page is about to be initialized. If you were to bind to the pageinit event, you'd be too late and have to initialize the header widget manually.



回答2:

As far as I know, you must include a header and footer within each data-role="page" container. If you wan't to avoid typing this out for each page, then I would require_once() a page in PHP that includes the header or footer, and use that in place of writing out a header and footer each time.

Sample:

<section data-role="page">
<?php require_once("header.php"); ?>

<div data-role="content">
<p>Hello world!</p>
</div>

<?php require_once("footer.php");?>
</section>

header.php:

<header data-role="header">
<h1>Title</h1>
</header>

footer.php:

<footer data-role="footer">
<<p>Footer content here</p>
</footer>


回答3:

Why more JS ?? ... instead of adding two elements for header and footer (either "header" and "footer" tags, or divs with appropriate classes, but mandatory with "position: fixed;") - and add padding top and bottom of the pages divs ? ... No JS code needed ... which will improves the performance ... although very little :) ...