2015-09-16 62 views

回答

0

您可以通過向所有鏈接添加eventListener或onclick事件來完成此操作。然後爲所有鏈接添加唯一的ID並將它們添加到cookie中。 當你加載你的應用程序,只需讀出創建的cookie,並更改類名類似「already_visited」

編輯:

<a id="link1" href="page1.html">link 1</a> 
<a id="link2" href="page2.html">link 2</a> 
<a id="link3" href="page3.html">link 3</a> 

<style type="text/css"> 
    .already_visited{ 
     color: #f00; 
    } 
</style> 


<script type="text/javascript"> 

    window.addEventListener("load", function function_name(argument){ 
     var links = eval(getCookie("links_visited")); 
     for(var i = 0; i < links.length; i++){ 
      document.getElementById(links[i]).classList.add("already_visited"); 
     } 
    }); 

    /* Add events to all links */ 
    function callback(e) { 
     var e = window.e || e; 

     if (e.target.tagName !== 'A'){ 
      return; 
     } 

     /* call cookie function */ 
     addToVisited(e.target.id); 
    } 

    if (document.addEventListener){ 
     document.addEventListener('click', callback, false); 
    } 
    else{ 
     document.attachEvent('onclick', callback); 
    } 

    /* cookie function */ 
    function addToVisited(link_id){ 
     var ids = getCookie("links_visited"); 

     if (ids == "") { 
      setCookie('links_visited', '["'+link_id+'"]', 365); 
     } 
     else if(ids.indexOf(link_id) == -1){ 
      var id_array = eval(ids); 
      id_array.push(link_id); 
      setCookie("links_visited", '["'+id_array.join('","')+'"]', 365); 
     } 

     console.log(getCookie("links_visited")); 
    } 

    /* cookie function helpers */ 
    function setCookie(cname, cvalue, exdays) { 
     var d = new Date(); 
     d.setTime(d.getTime() + (exdays*24*60*60*1000)); 
     var expires = "expires="+d.toUTCString(); 
     document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/"; 
    } 

    function getCookie(cname) { 
     var name = cname + "="; 
     var ca = document.cookie.split(';'); 
     for(var i=0; i<ca.length; i++) { 
      var c = ca[i]; 
      while (c.charAt(0)==' ') c = c.substring(1); 
      if (c.indexOf(name) == 0) return c.substring(name.length, c.length); 
     } 
     return ""; 
    } 

</script> 

的代碼應該是不言自明的,但問什麼是不清楚你

+0

我該如何添加id到cookie? –

+0

查看編輯答案 –

+0

鏈接是動態的問題(每個用戶可以在某些字段中輸入鏈接)。所以我不能給這個唯一的ID。 –