2017-09-20 15 views
0

왼쪽에는 탐색 링크가 있고 오른쪽에는 컨텐츠 div가있는 페이지가 있습니다. 탐색 링크 HTML은 이와 같이 설정됩니다. 내가 링크에 결합 브라우저 기록에 새로운 상태를 밀어 데이터 모드 값을 기준으로 해당 링크에 대한 내용을로드 할 생각이 아래와 같이AJAX로드 된 컨텐츠에 대한 브라우저 기록 조작

<a href="javascript:;" class="nav-link" data-mode="myModeValue">Test</a> 

나는 자바 스크립트 기능을 설정했습니다. FORWARD는 완벽하게 작동하지만, 뒤로 가끔씩 돌아가려면 이전 해시로 돌아가려면 두 번 클릭해야하며 이유는 확실하지 않습니다.

여기까지 제가 지금까지 있습니다.

<script language="javascript"> 
    // Create var indicating the CURRENT mode we're on - home being the default when page loads 
    currentMode = "home"; 
    // Push the default page (mode) into the history 
    history.pushState(null, document.title, location.pathname + "#!/detail-mode/" + currentMode); 

    // bind to my nav links 
    $(document).on('click', '.nav-link', function(e){ 
     e.preventDefault(); 
     ajaxLoadVehicleSearchDetailContent($(this).data('mode')); 
    }); 

    function ajaxLoadVehicleSearchDetailContent(mode) { 
     // Get the mode and link object 
     var thisMode = mode.toString().toLowerCase(); 
     var thisLink = $('a[data-mode="' + mode + '"]'); 
     // If we're switching to a different tab - continue 
     if (currentMode != thisMode) { 
      currentMode = thisMode;  
      // Get the content via AJAX 
      $.ajax({ 
       url: "/myAjaxFunctionFileURL", 
       type: "POST", 
       data: { method:"getTabContent", mode:thisMode }, 
       success: function(result) { 
        history.pushState(null, document.title, location.pathname + "#!/detail-mode/" + thisMode); 
        // Update the content area - fadeOut,replace,fadeIn 
        $('#contentArea').fadeOut(globalAnimationDuration, function() { 
         $('#contentArea').html(result).fadeIn(globalAnimationDuration); 
         $('.nav-link').removeClass('current'); 
         thisLink.addClass('current');     
        }); 
       } 
      });  
     } 
    } 

    // Listen for the popstate and load correct content when user goes BACK in history 
    window.addEventListener("popstate", function() { 
     if (location.hash.indexOf("#!") != -1) { 
      var thisMode = location.hash.split("/").slice(-1)[0];   
      ajaxLoadVehicleSearchDetailContent(thisMode);   
     } 
    }, false); 
</script> 

globalAnimationDuration VAR은 단순히

사람이 왜 다시 이상한 행동 갈 때 위에 약간의 빛을 수 (500)의 값을 가지는 변수? 또는 내가 수행 할 수있는 작업을 수행하는 방법을 보여주는 좋은 예라도 그에 따라 메서드를 업데이트 할 수 있습니까?

JSFiddle Here

감사합니다!

+0

블라인드 추측 : 버튼을 너무 빠르게 두 번 클릭하면 두 요청이 트리거되어 동일한 푸시 상태가 두 번 발생했을 가능성이 있습니까? 당신은 모든 pushstate를'console.log'해야합니다. 그것이 그렇다면, 프로세스가 끝날 때까지 (AJaxRequest가 성공했는지 실패했는지에 상관없이) 뒤로/풀다운 버튼을 모두 비활성화하십시오. – Walfrat

+0

그것을 파악해보십시오. 그것은 내 논리의 오류였습니다. 아래에 답변했습니다. – Phil

답변

0

알아 냈습니다. 앞뒤 탐색 모두에서 동일한 ajaxLoadVehicleSearchDetailContent을 호출 했으므로 뒤로 클릭 할 때 스택에 항목을 잘못 추가하고있었습니다. 그래서 그것은 스택에서 아이템을 pop하고, 현재 탭이 아니면 스택에 다시 추가 한 함수를 호출합니다.

내 솔루션에서 아래에 표시된대로 내 ajaxLoadVehicleSearchDetailContent() 메서드에 대한 추가 인수를 추가했습니다.

function ajaxLoadVehicleSearchDetailContent(mode,backward) { 
     // Get the mode and link object 
     var thisMode = mode.toString().toLowerCase(); 
     var thisLink = $('a[data-mode="' + mode + '"]'); 
     // If we're switching to a different tab - continue 
     if (currentMode != thisMode) { 
      currentMode = thisMode;  
      // Get the content via AJAX 
      $.ajax({ 
       url: "/myAjaxFunctionFileURL", 
       type: "POST", 
       data: { method:"getTabContent", mode:thisMode }, 
       success: function(result) { 
        if (!backward) history.pushState(null, document.title, location.pathname + "#!/detail-mode/" + thisMode); 
        // Update the content area - fadeOut,replace,fadeIn 
        $('#contentArea').fadeOut(globalAnimationDuration, function() { 
         $('#contentArea').html(result).fadeIn(globalAnimationDuration); 
         $('.nav-link').removeClass('current'); 
         thisLink.addClass('current');     
        }); 
       } 
      });  
     } 
    } 

그런 다음 내 탐색 링크에서 호출 할 때 false를 보내고 popstate 이벤트에서 호출하면 true를 호출합니다.