2014-07-26 2 views
0

JavaScript를 사용하여 최근에 본 제품을 표시하거나 숨길 수 있습니다.페이지에 클래스 유지 (자바 스크립트 쿠키 포함)

페이지로드시 최근에 본 제품이 포함 된 div가 닫히도록 설정됩니다. 사용자가 표제를 클릭하면 열립니다. 그러나 사용자가 div를 연 다음 다른 제품 페이지로 이동하면 동일한 div가 다시 닫힙니다 (분명히).

페이지로드 후 div를 열어두기 위해 JavaScript 쿠키를 사용해야한다는 것을 알고 있습니다. 여러 가지 자습서를 살펴 보았지만 그 방법이 내 고유 한 상황과 어떤 관련이 있는지 이해할 수 없습니다. 누구든지 어떤 제안이 있습니까?

나는 현재 자바 스크립트를 사용하고 있습니다 :

$(document).ready(function() { 
    $("#recent-products-wrap > h3").on("click", function(e){ 
     if($(this).parent().has("ul")) { 
      e.preventDefault(); 
     } 
     if(!$(this).hasClass("closed")) { 
     // open our new menu and add the open class 
      $(this).next("ul").slideUp(350); 
      $(this).addClass("closed"); 
      $("#recent-products-wrap > h3").removeClass("recent-products-minus"); 
      $("#recent-products-wrap > h3").addClass("recent-products-plus"); 
     } 
     else if($(this).hasClass("closed")) { 
      $(this).removeClass("closed"); 
      $(this).next("ul").slideDown(350); 
      $("#recent-products-wrap > h3").removeClass("recent-products-plus"); 
      $("#recent-products-wrap > h3").addClass("recent-products-minus"); 
     } 
    }); 
}); 

답변

1

당신이 사용할 수있는 쿠키를 만들려면 :

document.cookie="div_viewed=true"; 

쿠키를 읽으려면이 사용할 수 있습니다

var x = document.cookie; //return a STRING, e.g. div_viewed=true 

귀하의 경우 다음과 같이됩니다 :

,
$(document).ready(function() { 
    //check the cookie here 
    if(document.cookie.length > 0){ 
     if(document.cookie.indexOf("div_viewed=true") >= 0) 
       //div is on opened position 
     else 
       //div is on closed position 
    } 

    $("#recent-products-wrap > h3").on("click", function(e){ 
     if($(this).parent().has("ul")) { 
      e.preventDefault(); 
     } 
     if(!$(this).hasClass("closed")) { 
     // open our new menu and add the open class 
      document.cookie="div_viewed=true"; 
      $(this).next("ul").slideUp(350); 
      $(this).addClass("closed"); 
      $("#recent-products-wrap > h3").removeClass("recent-products-minus"); 
      $("#recent-products-wrap > h3").addClass("recent-products-plus"); 
     } 
     else if($(this).hasClass("closed")) { 
      document.cookie="div_viewed=false"; 
      $(this).removeClass("closed"); 
      $(this).next("ul").slideDown(350); 
      $("#recent-products-wrap > h3").removeClass("recent-products-plus"); 
      $("#recent-products-wrap > h3").addClass("recent-products-minus"); 
     } 
    }); 
}); 

더 많은 정보를 들어, 답변이 documentation ...

+0

많은 감사를 확인합니다. 나는 이것을 알아 내려고 노력하는 시간을 보냈다! 제안을 사용하여 쉽게 쿠키를 만들 수있었습니다. 그러나 "if (document.cookie =="코드가 제대로 작동하지 않는 것 같습니다.) 결국 JQuery Cookies Plugin (https://github.com/carhartl/jquery-cookie)을 사용했습니다. 다시 한 번 감사드립니다. – Ben

+1

다행이라고 생각하면 다행이라고 생각하면 옳은 답과 득표로 표시하는 것을 잊지 마십시오. –