2014-12-04 1 views
1

쿠키로 DIV의 값을 저장하는 것보다 스크립트에 의해 기록 된 데이터와 DIV를 채우는 대지. 이 스크립트는 특정 div에 내용을 씁니다.jQuery를/자바 스크립트 : 자바 스크립트 스크립트가 외부에서</p> <p>사용자가 메뉴 항목 위로와 호버에 놓을라고 : 나는 다음과 같은 시나리오를 한

내가해야 할 일은이 divs HTML을 가져 와서 쿠키에 저장하는 것입니다. 3 분 후에 쿠키가 만료됩니다.

외부 사이트에서 자바 스크립트를 호출하는 대신 쿠키가 아직 만료되지 않은 3 분 안에 사용자가 두 번째로 이동하면 Javascript로 div에 이전에 작성한 HTML을로드해야합니다. 외부 사이트. 이것은 서버에 대한 각 호출에 대해 요금을 부과하기 때문에 외부 사이트에 대한 통화량을 제한하는 것입니다.

외부 사이트의 Javascript에서 내용을 쓰고 쿠키에 쓰여진 html 값을 할당하는 것이 클라이언트 측에서 동시에 일어나기 때문에 html을 저장할 때 아무런 가치도 얻지 못하기 때문에 쿠키.

어떻게 든 페이지가 완전히로드 될 때까지 기다려야하므로 외부 스크립트가 HTML 콘텐츠로 지정된 div를 채운 다음 해당 divs HTML 콘텐츠를 쿠키에 추가합니다.

이것은 내가 붙어있는 곳이며, 더 쉽고 똑똑한 접근 방법이 있습니까? 저는 제안과 아이디어에 열려 있습니다!

$(document).ready(function() { 

    // create script element 
    var my_script = document.createElement('script'); 
     my_script.type = 'text/javascript'; 
     my_script.src = "http://www.external-site.com/this_script_writes_content_to_div.js"; 

    // User hovers on a menu item, limit the call by using jQuery .one 
    $("#my_menu_item").one("mouseenter", function() { 

     // If cookie exists, don't write Javascript (my_script) but use stored value in cookie 
     if (document.cookie.indexOf("my_cookie") != -1) { 

      // This is where I'm having trouble, since the cookie's value is empty, see below 
      $("#div_with_content_from_js").html(getCookie("my_cookie")); 

      // Test results 
      console.log('Cookie exists'); 
      console.log(getCookie("my_cookie")); 
     } 

     // If cookie does not exist, write the script to a div 
     // the script will then populate another div with content, the div name is 'div_with_content_from_js' 
     // then create cookie and store the other divs content into the cookie 
     else { 
      document.getElementById("div_for_external_script").appendChild(my_script); 
      create_my_cookie(); 

      // test results 
      console.log('Cookie does not exist'); 
     } 
    }); 

}); 


// Creates a cookie that expires after 180 seconds (3 minutes) 
function create_my_cookie() { 
    var date = new Date(); 
    date.setTime(date.getTime() + (180*1000)); 
    var expires = "; expires="+date.toGMTString(); 

    // this value returns empty because the html value of div_with_content_from_js was just written (see else part above) 
    // this is where I'm stuck, how do I get the value of div_with_content_from_js and store it in the cookie 
    var coffee_cookie_value = $("#div_with_content_from_js").html(); 

    document.cookie = 'my_cookie' + "=" + coffee_cookie_value + expires + "; path=/"; 

    // test results 
    console.log(coffee_cookie_value); 
    console.log(getCookie("my_cookie")); 
} 


// This function returns a specific cookie, used for testing 
function getCookie(name) { 
    var re = new RegExp(name + "=([^;]+)"); 
    var value = re.exec(document.cookie); 

    return (value != null) ? unescape(value[1]) : null; 
} 
+0

왜 초기 호버에 쿠키 값을 설정하지 않았습니까? (쿠키) { ㅋ ㅋ ㅋ ㅋ } 다른 { 전화 외부 스크립트 및 반환 세트 DIV 내용 에} 논리 dm4web –

답변

4
  1. 쿠키는
  2. 숨겨진 DIV 스토어에서 페이지
  3. 에 숨겨진 사업부를 추가 카운트 다운으로 만 사용 삼분되어 여기

    는 의견과 내가 가지고있는 코드입니다 외부 웹 사이트의 콘텐츠
  4. 호버시 : 만료되지 않은 경우 3 분 숨겨진 div의 콘텐츠를 복사하십시오.
+2

감사 @ 말이 있다면 , 나는이 시도 줄 것이다. 코딩 할 때 터널 비전에 들어갈 때가 있으며 alt 솔루션에 대해 생각하는 것을 잊어 버리는 경우가 있습니다. 쿠키에 정보를 저장하려고 계속했습니다./결과와 함께 게시합니다. – IntricatePixels

1

여기에 jQuery .always() 함수를 사용 하시겠습니까? jQuery에서 "always"함수는 위의 코드가 해결 된 후에 실행됩니다.

$("div_for_external_script").appendChild(my_script).always(function() { create_my_cookie(); }; 
0

MutationObserver을 사용하지 않으시겠습니까? 그러면 필요할 때마다 쿠키를 설정할 수 있습니다. 샘플 fiddle setTimeout은 데모 용입니다. 그래서 귀하의 코드는 다음과 같아야합니다 :

// If cookie does not exist, write the script to a div 
// the script will then populate another div with content, the div name is 'div_with_content_from_js' 
// then create cookie and store the other divs content into the cookie 
else { 
    var target = document.querySelector('#div_that_will_be_populated'); 
    var observer = new MutationObserver(function(mutations) { 
     mutations.forEach(function(mutation) { 
      if(mutation.type == 'childList') { 
       create_my_cookie(); 
      } 
     });  
}); 
var config = { attributes: true, childList: true, characterData: true }; 
observer.observe(target, config); 
document.getElementById("div_for_external_script").appendChild(my_script); 

// test results 
console.log('Cookie does not exist'); 
} 
관련 문제