2012-11-07 2 views
10

페이지를 업데이트하지 않고 브라우저 기록을 업데이트하는 동안 3 개의 링크를 사용하여 단순한 전체 History.js 예제를 전체 페이지에서로드 할 수있었습니다. 여기 이것이 History.js를 사용하는 적절한 방법입니까?

는와 관계있는 코드 조각이다 - 완전한 작동 예는 여기 http://jsfiddle.net/PT7qx/show

<a href="/page-header">Page Header</a> 
<a href="/login-form">Login Form</a> 
<a href="/nothing">Nothing</a> 

<script> 
var History = window.History; 
if (!History.enabled) { 
    return false; 
} 

History.Adapter.bind(window, 'statechange', function() { 
    var State = History.getState(); 
    History.log(State.data, State.title, State.url); 

    if (State.title == 'Page Header') { 
     $('#content').load('/user/login/ .pageHeader > *'); 
    } 

    if (State.title == 'Login Form') { 
     $('#content').load('/user/login/ #common-form > *'); 
    } 

    if (State.title == 'Nothing') { 
     $('#content').empty() 
    } 
}); 

$('body').on('click', 'a', function(e) { 

    var urlPath = $(this).attr('href'); 
    var Title = $(this).text(); 
    History.pushState(null, Title, urlPath); 

    // prevents default click action of <a ...> 
    return false; 
}); 
<\script> 

이다 나는 이것이 올바른 사용법이 있는지 알고 싶습니다. 이전 버전에서는 # urls를 사용하여 이벤트에 바인딩 할 수있었습니다. .on() 클릭 이벤트를 사용하여 History를 호출하고 거기에서 클릭 한 링크를 정렬하여이 최신 버전의 URL에 이벤트를 바인딩하는 예는 보지 못했습니다.

이 예를 위해 이것이 최선의 방법인지 확실하지 않습니다.

답변

22

더 많은 작업을 마친 후 최신 History.js를 사용하는 방법에 대한 간단한 예제를 작성했습니다. "(: {window.location.pathname() URLPath로서}, $ 여기에 내가 파티에 조금 늦었 HTML fragments hosted on Github

<!DOCTYPE html> 
<html> 
    <head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
    <title>Simple History.js Ajax example by dansalmo</title> 

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script> 
    <script type="text/javascript" src="http://balupton.github.com/history.js/scripts/bundled/html4+html5/jquery.history.js"></script> 

    <style type='text/css'> 
     .hidden { 
     display: none; 
     visibility: hidden; 
     } 
    </style> 
    </head> 
    <body> 
    <a href="/home">Home</a> 
    <a href="/about">About</a> 
    <a href="/contact">Contact</a> 
    <a href="/other">Other</a> 

    <p>The whole page will not re-load when the content below is updated, yet the URL is clean and the back button works!<p><br /> 
    <div id="content"> 
     <div id="home">Home Page content</div> 
    </div> 
    <br /> 
    <p>The content div will be updated with a selected div fragment from an HTML file hosted on github, however the broswer will see each content update request as a part of the page history so that the back button can be used.</p> 
    <br /> 
    <p>Adding more menu items is as simple as adding the new links and their corresponding html fragments.<p> 
    <div id="hidden_content" class="hidden"></div> 
    </body> 
    <script type='text/javascript'>//<![CDATA[ 
    $(function(){ 
    var History = window.History; 
    if (History.enabled) { 
     State = History.getState(); 
     // set initial state to first page that was loaded 
     History.pushState({urlPath: window.location.pathname}, $("title").text(), State.urlPath); 
    } else { 
     return false; 
    } 

    var loadAjaxContent = function(target, urlBase, selector) { 
     $(target).load(urlBase + ' ' + selector); 
    }; 

    var updateContent = function(State) { 
     var selector = '#' + State.data.urlPath.substring(1); 
    if ($(selector).length) { //content is already in #hidden_content 
     $('#content').children().appendTo('#hidden_content'); 
     $(selector).appendTo('#content'); 
    } else { 
     $('#content').children().clone().appendTo('#hidden_content'); 
     loadAjaxContent('#content', State.url, selector); 
    } 
    }; 

    // Content update and back/forward button handler 
    History.Adapter.bind(window, 'statechange', function() { 
     updateContent(History.getState()); 
    }); 

    // navigation link handler 
    $('body').on('click', 'a', function(e) { 
     var urlPath = $(this).attr('href'); 
     var title = $(this).text(); 
     History.pushState({urlPath: urlPath}, title, urlPath); 
     return false; // prevents default click action of <a ...> 
    }); 
    });//]]> 

    </script> 
</html> 
+0

의 아약스로드를 수행 working jsfiddle example이지만, 그'History.pushState을 (주목할 필요가 title "). text(), State.urlPath);'window.location.pathname()은 함수가 아니므로 오류가 발생합니다. 그냥 괄호를 제거하면 매력처럼 작동합니다. – indextwo

+0

잡기에 감사드립니다. 내가 작업중인 버전에서 그것을 붙여 넣고 있다고 생각했기 때문에 내가 어떻게 그것을 놓쳤는 지 잘 모르겠습니다. – dansalmo

+0

@dansalmo, 위 예제 (http://stackoverflow.com/a/13314438/1867808)와 같은 예제를 구현하면 index.html 파일과 관련하여 추가 컨텐츠를 어디에 배치해야합니까? index.html과 같은 폴더에있는 response.html에 넣습니까? –

관련 문제