code

jQuery Mobile 및 PhoneGap에서 템플릿 / 지속적 머리글 / 바닥 글 템플릿 만들기

codestyles 2020. 12. 2. 21:22
반응형

jQuery Mobile 및 PhoneGap에서 템플릿 / 지속적 머리글 / 바닥 글 템플릿 만들기


jQuery Mobile / PhoneGap으로 모바일 앱을 작성하는 중입니다. HTML / JS를 사용하여 페이지를 만드는 이 샘플 템플릿사용하여 시작합니다. <page>하나의 단일 html 파일에 모든 태그를 포함하는 것이 아니라 편집하기 쉽도록 분할되어 있습니다.

각 페이지에 대해 별도의 파일이 있으므로 임시 머리글 / 바닥 글을 포함하는 가장 좋은 방법은 무엇입니까? 각 HTML 페이지에 전체 footer-> navbar 코드를 복사하여 붙여 넣어야하는 부분 만 보았습니다. 이것은 당연한 것 같지 않습니다. 예를 들어 하나의 메뉴 항목을 변경하려면 각 페이지로 이동하여 변경해야합니다.

내가 놓친 해결책은 무엇입니까?

어쩌면 jQuery Mobile을 이해하지 못할 수도 있습니다. 예를 들어, 문서에 사용하는 사이드 바가 있습니다. 사이드 바 코드가 각 페이지에 복사되어 붙여 집니까? 말이 안 돼. 바닥 글에 대해 여기에서 묻는 질문과 같은 생각입니다.

http://jquerymobile.com/test/docs/pages/page-cache.html

이것은 내가 옳지 않은 것 (그리고 $.live('pageinit')작동 하지 않는 것 )을 가지고 있습니다. 이 HTML은 각 HTML 페이지에 표시됩니다.

<div id="mainFooter" data-position="fixed" data-id="mainFooter" data-role="footer" class="ui-footer ui-bar-a ui-footer-fixed fade ui-fixed-inline" role="contentinfo" style="top: 58px;">

그리고 JS

$.live('pageinit', function (event) {
    displayFooter();
});

function displayFooter() {
    $('#mainFooter').html('<div data-role="navbar" class="nav-glyphish-example" data-grid="d">' +
        '<ul>' +
        '<li><a href="#" id="menuitem1" data-icon="custom">Menu Item 1</a></li>' +
        '<li><a href="#" id="menuitem2" data-icon="custom">Menu Item 2</a></li>' +
        '<li><a href="#" id="menuitem3" data-icon="custom">Menu Item 3</a></li>' +
        '</ul>' +
        '</div>');
}

나는 며칠 동안이 문제를 해결하려고 노력해 왔으며 해결책에 정말 가까워졌습니다. 다음 HTML을 사용합니다.

<body>
    <div data-role="page" id="page">

        <div data-role="header">
            <h1 id="title">Title</h1>
        </div><!-- /header -->

        <div data-role="content" id="content">  
            <p>Loading...</p>
        </div><!-- /content -->

        <div data-role="footer" id="footer" data-position="fixed">
            <div data-role="navbar" id="navbar">
            </div>
        </div><!-- /footer -->
    </div><!-- /page -->
</body>

그리고 ajax를 사용하여 메뉴 / 콘텐츠를로드하기 위해 다음 함수를 만들었습니다.

$(document).on('pageinit', "#page", function() {
    // for example: displayFooter();
    loadContent("main");
    loadMenu("default");
});

function loadContent(location) {
    return $('#content').load("views/content/"+location+".html", function() { 
        $(this).trigger('create');
    });
}
function loadMenu(location) {
    $("#menu").remove();
    $("#navbar").remove();

    $("#footer").html('<div data-role="navbar" id="navbar">');
    $("#navbar").html('<ul id="menu"></ul>');

    $("#menu").load("views/menus/"+location+".html", function() { $("#menu").parent().navbar(); });

    return true;
}

.trigger('create');하고 .navbar();있지만, 여전히 하나 약간의 버그가있어, 올바른 스타일링 JQM을 유지하는 데 필요한 방법이다. 메뉴의 위치 (css top : ... px를 사용하여 설정 됨)가 때때로 정확하지 않으며 첫 번째 탭 후 올바른 위치로 이동합니다. 그래도 정말 가깝습니다!

편집 : 위에서 언급 한 사소한 버그 로 설정 #footer하면 position: fixed;사라집니다. 또한 JQM 에 의한 값으로 인한 위치 가 잘못된 경우 top(px 단위)를 계산하는 방법을 쉽게 만들 수 있습니다.#footertop


이 같은:

function getText() {
    //return footer text here
}


$("div:jqmData(role='page')").live("pagebeforecreate",function() {
    // get find the footer of the page
    var $footer =$(this).page().find('div:jqmData(role="footer")')
    // insert it where you want it... 
}

getText에서 role = footer를 정의하고 정의되었는지 확인하기 만하면됩니다. 그렇지 않은 경우 추가합니다.


이 작업을 제대로 수행하려면 Thorax 또는 JavascriptMVC와 같은 js 프레임 워크를 살펴 봐야합니다.

In a JMVC app, you could do this from any view:

<div data-role="page">
    <%== $.View('./header.ejs') %>
    <div data-role="content">
    ...
    </div>
    <%== $.View('./footer.ejs') %>
</div>

jQuery Mobile is really only useful for progressive markup enhancement and styling for mobile devices. For the actual MVC part you need an MVC framework.

The examples for jQuery Mobile are also mostly geared for building mobile web sites which since they fetch pages from a server assume your code reuse is happening server side. A phonegap app is a whole nother beast since you will be generating these pages on the fly or from local static files. This is were the MVC framework comes in as you would be building your pages using controllers, views, view helpers, and model classes. You tie all that into jQuery mobile by listening to the pagebeforeshow event as shown on the jQm documentation page on scripting pages


We haven't found a good way to do this yet either. So we are actually handling this dynamically in our custom js file. Looking for the closing container - and then dynamically appending the footer after the last content div closes.


Depends how you load the respective pages.

If you use rel="external" - no AJAX, each page will be reloaded completely.

If you use regular JQM - AJAX, JQM will grab the page and attach it to your existing DOM. Think of your first page as your "anchor" page, which all subsequent pages are added/removed.

In the 2nd case you could specify a data-append-to-all-pages="true" attribute on elements you want to have on every page.

Then just listen to the respective event (pagebeforeshow?) and add elements with the above label to the new page before it's shown. This way elements would only have to be set on the first page and then automatically be added to any subsequent page being pulled in and added to the DOM.

I'm looking into this right now with a login form, which I need on every page outside the login and have to avoid ending up with duplicate input#someID.

EDIT - possible solution

Put the respective element on the first page and add unique attributes, like so:

 <div data-role="navbar" data-unique="true" data-unique-id="log">
     // full navbar
 </div>

All other pages just get the unique element container

<div data-role="navbar" data-unique="true" data-unique-id="log"></div>

Then use this script:

$('div:jqmData(role="page")').live('pagebeforehide', function(e, data) {

    //  check page you are leaving for unique items 
    $(this).find('div:jqmData(unique="true")').each(function(){

         // more or less 1:1 stickyFooter
         var uniqueID = $(this).jqmData("unique-id"),
             nextPage = data.nextPage,
             nextUnique = nextPage && nextPage.find( "div:jqmData(unique-id='"+uniqueID+"')" ),
             nextMatches = nextUnique.length && nextUnique.jqmData('unique-id') === uniqueID;

         // if unique items on previous and new page are matching
         if ( uniqueID && nextMatches ) {
            nextUnique.replaceWith( uniqueID );
            $(this).jqmData("unique-id").empty();
            }
         });
     }); 

Of course this would mean you need the unique container on every page. But then you would just carry the content of it along as you traverse through the app. Should work for me and avoid having the same login form 2+ times inside the DOM.

Plus you would be free to edit it's contents for example adding active class.


Don't use pageinit, the events that you should listen for are pagecreate and pageshow, pagecreate gets called the first time a page is loaded, but not when you navigate back to the page, e.g. on back button. Whereas pageshow fires everytime a page is shown, so just bind a live listener to the pageshow event for every page where you add your footer (assuming your footer may change, otherwise use pagecreate).

I have a longer example that shows you how to bind to the event properly in another question: https://stackoverflow.com/a/9085014/737023

And yes a great solution is just to use a PHP/CF include, which is what I use instead of JS.


EDIT My bad, seems pageinit is now used instead of pagecreate (see here), but it still stands that pageshow fires every time a page is shown - so you can use those as you need

참고URL : https://stackoverflow.com/questions/9152446/creating-templated-persistant-header-footer-template-in-jquery-mobile-and-phoneg

반응형