我有一个div
,其中包含多个a
标记,每个标记都包含一个唯一的href
属性。单击后,每个链接都标有复选标记。我正在尝试为点击设置会话cookie,这样当用户离开并返回页面时,指示跟随链接的复选标记仍然存在。我已经设置了一个数组(strArray
),它通过将history
对象转换为字符串并使用.push()
方法来存储cookie,以检查hrefs
数组通过以下方式生成:
var urlArray = $(".holder a").map(function() {
return $(this).attr("href");
}).get();
我无法弄清楚为什么strArray
会在点击链接或我的脚本达到预期结果后不断被重写,也就是说,如果它实际上是在导航离开页面之前预先添加链接并返回再次。有人能指出我正确的方向吗?
答案 0 :(得分:1)
正如charlietfl所提到的,本地存储更适合这种情况,我会这样做:
<强> 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();
});