2013-06-08 2 views
5

jquery $ .ajax를 사용하여 웹 사이트를 개발하고있어 콘텐츠/디렉토리에있는 다른 페이지의 콘텐츠를로드합니다. 또한 해시 태그를 사용하여 뒤로 버튼, 다시로드 등을 활성화합니다.AJAX 뒤로 버튼 메뉴 문제

하지만. 활성 항목이있는 주 메뉴가 있는데, 한 주 메뉴 항목의 깊이있는 페이지 사이를 탐색하면 활성화됩니다. 그런 다음 주 메뉴 항목 중 하나를 클릭합니다 (예 : 연락처). 따라서 연락처 메뉴 항목이 활성화됩니다. 그리고 브라우저의 뒤로 버튼을 클릭하면 활성 메뉴 항목이 변경되지 않습니다.

활성 주 메뉴 항목의 상태를 기억하는 방법이 있습니까? 주 메뉴는 컨테이너 페이지에 있습니다.

감사합니다.

$(function(){ 

     $('.menu a') 
      .bind('click',function(e) { 
       e.preventDefault(); 
       $('#content').html('Извините, страница не существует или находится в разработке!'); 
       $('.menu a').each(function() {$(this).removeClass('activelink');}); 
       location.hash=$(this).attr('href').match(/(([a-z]*)\W)*/)[2]; 

       $(this).addClass('activelink'); 
       return false; 
      }); 

     $('#content').on('click','a',function(e) { 
      if (!($(this).hasClass('address') || $(this).hasClass('zoom'))){ 
      e.preventDefault(); 
      $('#content').html('Извините, страница не существует или находится в разработке!'); 
      location.hash=$(this).attr('href').match(/(([a-z]*)\W)*/)[2]; 
      return false; 
      } 
      else { 
       if ($(this).hasClass('address')) { 
       alert('Вы покидаете сайт The House Of Events. Возвращайтесь к нам еще!'); 
       } 
      } 
     }); 

    function hashChange(){ 
     var page=location.hash.slice(1); 
     if (page!=""){ 
      $.ajax({ 
        type: "GET", 
        url: "content/" + page + ".html #sub-content", 
        success: function(data, status) { 
         $('#content').html(data); 
         }, 
        error: function fail() { 
         $('#content').html('Error'); 
         } 
       }); 
     } 
    } 

    if ("onhashchange" in window){ 
     $(window).on('hashchange',hashChange).trigger('hashchange'); 
    } else { 
     var lastHash=''; 
     setInterval(function(){ 
      if (lastHash!=location.hash) 
       hashChange(); 
      lastHash=location.hash; 
     },100); 
    } 
}); 
+0

메뉴 항목을 활성화하는 방법을 보려면 기본 메뉴 코드를 참조하십시오. – Nagarjun

+0

추가했습니다. 코드 –

+0

체크 아웃'history.pushState()' –

답변

0

태그를 해킹하는 경우 작은 트릭을 만들 수 있습니다.

편집이 :

$('#content').on('click','a',function(e) { 
    if(!($(this).hasClass('address') || $(this).hasClass('zoom'))){ 
    e.preventDefault(); 
    $('#content').html('Извините, страница не существует или находится в разработке!'); 
    var page=location.hash.slice(1).split('/')[0] + '/' + $(this).attr('href').match(/(([a-z]*)\W)*/)[2]; 
    location.hash=page; 
    return false; 
    } else { 
    if ($(this).hasClass('address')) { 
     alert('Вы покидаете сайт The House Of Events. Возвращайтесь к нам еще!'); 
    } 
    } 
}); 

function hashChange(){ 
    var page=location.hash.slice(1).split('/')[1]; 
    if(page==='undefined'){ 
    page=location.hash.slice(1).split('/')[0]; 
    } 
    if(page!=""){ 
    $.ajax({ 
     type: "GET", 
     url: "content/" + page + ".html #sub-content", 
     success: function(data, status) { $('#content').html(data); }, 
     error: function fail() { $('#content').html('Error'); } 
    }); 
    } 
} 

은 또한 HTML5의 역사 API를 사용할 수 있습니다.

onpopstate

window.onpopstate = function(e){ 
    if(e.state){ 
    $('.menu a.activelink).removeClass('activelink') 
    $('.menu #'+JSON.stringify(e.state.menu).replace(/"/gi,'')).addClass('activelink'); 
    var url=window.location.pathname; 
    $.ajax({ ... }) 
    } 
} 

를 사용 (위치 해시를 삭제) 다음

var active=$('.menu a.active').attr('id'); // or var active=$('.menu a.active').text(); 
history.pushState({menu: active}, "Our events", "events.html"); 

가 다시 버튼으로 물건을 변경하는 클릭 이벤트에 따라 본을 넣어 그리고 당신은 많은을 추가 할 경우 반드시 바보 같은 방법을 finali 메뉴 항목에 클래스를 입력하고 확인하십시오. .hasClass()

+0

감사하지만 문제는 주 메뉴에없는 페이지와 연결되어 있습니다. 예를 들어, 내 경로는 다음과 같습니다. 메인 메뉴 항목 인 "Our events"를 클릭했습니다 -> "Weddings"페이지의 콘텐츠 페이지 링크를 클릭하고 클릭 한 후 내 콘텐츠 div에로드했습니다. 하지만이 페이지는 "우리 이벤트"의 멤버이기도하므로 메인 메뉴에서 "연락처"-> 클릭 한 후 다시 브라우저 버튼을 클릭했지만 활성화되어 있어야합니다. 그러나 결혼식에 대한 링크가 없다는 것을 알았습니다 .html을 주 메뉴에 표시하므로 "연락처"항목이 여전히 활성 상태입니다. 그리고 "연락처"대신 "우리 이벤트"항목을 활성화해야합니다. –

+0

그러면 두 가지 방법이 있습니다. 먼저 하위 링크의 이름 인 메뉴에 클래스를 추가합니다. 두 번째 옵션은 HTML5 기록 API를 사용하는 것이며 'stateObj'처리기를 사용하여 활성 상태 (JSON을 사용해야 함)로하려는 메뉴의 이름을 추가 할 수 있습니다. 그리고 'JSON.stringify (e.state.name_of_the_handler)'로 해당 정보를 호출하여 데이터를 가져옵니다. – Nergal

+0

또는 yourdomain.com/#/weddings/our_events를 사용하고 'location.hash.slice (1) .split ("/") [1]'을 사용할 수 있습니다. 어쩌면 해시 태그를 사용하려는 경우 가장 좋은 해결책 일 수 있습니다. – Nergal