如果cookie存在则预先加载

时间:2016-10-12 01:45:54

标签: javascript jquery cookies

我有一个div,其中包含多个a标记,每个标记都包含一个唯一的href属性。单击后,每个链接都标有复选标记。我正在尝试为点击设置会话cookie,这样当用户离开并返回页面时,指示跟随链接的复选标记仍然存在。我已经设置了一个数组(strArray),它通过将history对象转换为字符串并使用.push()方法来存储cookie,以检查hrefs数组通过以下方式生成:

var urlArray = $(".holder a").map(function() {
  return $(this).attr("href");
}).get();

我无法弄清楚为什么strArray会在点击链接或我的脚本达到预期结果后不断被重写,也就是说,如果它实际上是在导航离开页面之前预先添加链接并返回再次。有人能指出我正确的方向吗?

请看我的小提琴:https://jsfiddle.net/tfrx9tyf/19/

1 个答案:

答案 0 :(得分:1)

正如charlietfl所提到的,本地存储更适合这种情况,我会这样做:

Working jsFiddle

<强> HTML:

<a href="https://somesite/index.php" class="remember-links">some link</a>
<br>
<a href="https://somesite/home.php" class="remember-links">some other link</a>
<br>
<button class="remove-remembered">Remove remembered </button>

<强> JS

/**
 * Feature detect + local reference for simple use of local storage
 * if (storage) {
 *    storage.setItem('key', 'value');
 *    storage.getItem('key');
 * }
 *
 */
var storage;
var fail;
var uid;
try {
  uid = new Date;
  (storage = window.localStorage).setItem(uid, uid);
  fail = storage.getItem(uid) != uid;
  storage.removeItem(uid);
  fail && (storage = false);
} catch (exception) {}
/* end  Feature detect + local reference */




$(document).on('click', '.remember-links', function(e) {
  var $this = $(this);
  if (storage) {
    var thisLink = $this.attr('href'); // get the clicked href
    var links = storage.getItem('rememberedLinks'); // get all the previously clicked links as a string
    links = (!links || links == '') ? [] : links.split('||'); // if present, split the links into an array, or just make an empty array
    if ($.inArray(thisLink, links) === -1) links.push(thisLink); // if the link is not already in the list, add it
    console.log(links);
    links = links.join('||'); // join the array into a string sepparated by a string not likely to appear in an actuall link "||"
    storage.setItem('rememberedLinks', links); // store the new value
    $this.addClass('remembered');
  } 
});


$(document).on('click', '.remove-remembered', function(e) {
  if (storage) {
    storage.setItem('rememberedLinks', '');
    $('.remembered').removeClass('remembered');
  }
});

function checkLinks() {
  if (storage) {
    var links = storage.getItem('rememberedLinks') || ''; // get all the previously clicked links as a string
    console.log(links);
    links = (!links || links == '') ? [] : links.split('||'); // if present, split the links into an array, or just make an empty array
    console.log(links);
    $('.remember-links').each(function() {
      var $this = $(this);
      var thisLink = $this.attr('href'); // get the current href 
      if ($.inArray(thisLink, links) > -1) $this.addClass('remembered'); // if remembered, do something with the link in the dom
    });
  }
}



// on load, check the links to see if they need to be marked.
$(function() {
  checkLinks();
});
相关问题