我试图阻止添加类.activeAdv如果其中的链接将其URL存储在cookie中,如果用户单击链接则添加此cooke,所以基本上我试图停止返回用户单击相同链接两次。
默认情况下,链接隐藏在div下面,该div在添加.activeAdv类时显示动画,显示链接。
下面是当前代码以及项目的codepen示例。我猜我需要将activeAdv addClass包装在IF条件中:
我认为我有正确的想法,并且只要点击链接设置cookie,我就会在IF声明中苦苦挣扎,有人可以帮忙吗?
http://codepen.io/Jambob/pen/wKyoRr
<article>
<div id="on-1" class="box">
<h2>1 dec</h2>
</div>
<div class="present">
content
<a href="http://www.google.com">www.google.com</a>
</div>
</article>
// Checks for content within .present, if TRUE adds .activeAdv animation class
$(".present").filter(function(){
return $(this).html().trim().length > 0;
}).parent().addClass('activeAdv');
// When link clicked, store its URL in cookie
$( ".present a" ).click(function() {
$.cookie($(this).attr('href'), true);
});
if ( '(".present").html().trim().length > 0;' ) {
if ( '(".present a").attr("href")' === "http://www.google.com") {
$(this).parent().addClass('activeAdv');
}
}
经过一番思考后,我想出了一个不同的IF语句,可能是沿着正确的方向
// Checks if content exists
if ( '(".present").html().trim().length > 0;' ) {
// Checks if HREF of child link matches existing cookie (using a string for testing)
if ( '(".present a").attr("href")' === "http://www.google.com") {
$(this).parent().addClass('activeAdv');
}
}
答案 0 :(得分:0)
因此,如果:visited
CSS伪类不够(它与访问过的链接相匹配),您可以使用localStorage
,它更专注于此目的。我创建了可以在Firebug控制台上运行的脚本并为未访问的链接着色:
(function(links) {
// Load visited links from local storage
var visited = JSON.parse(localStorage["visited"]||"[]");
// Safety check
if(!visited instanceof Array) {
visited = [];
localStorage["visited"] = [];
}
function setClassToLinks() {
links.each(function(){
// Remember state - asume not visited
var linkVisited = false;
// Check for inner HTML
if(this.innerHTML.trim().length > 0) {
// Check if in list of visited links
if(visited.indexOf(this.href)==-1)
linkVisited = true;
else
console.log("Already visited: "+this.href);
}
else
// Skip empty links
return console.log("No inner HTML.");
// Reset color
this.style.color = !linkVisited?"":"red";
// And remove class
if(linkVisited)
$(this).removeClass("activeAdv");
else
$(this).addClass("activeAdv");
})
}
setClassToLinks();
// When link clicked, store its URL in LocalStorage
links.click(function() {
// Prevent duplicities
if(visited.indexOf(this.href)==-1) {
visited.push(this.href);
localStorage["visited"] = JSON.stringify(visited);
}
});
// [OPTIONAL] Update links realtime - triggers when local storage changes
window.addEventListener('storage', function (event) {
if(event.key=="visited") {
visited = JSON.parse(localStorage["visited"]||"[]");
// Change CSS
setClassToLinks();
}
});
})($("a"));
我的解决方案的一个方面是,当您在不同的选项卡中浏览时,链接会自动更新(如果此选项卡已运行脚本)。
visited
数组可能会快速增长,这就是为什么我认为cookie是一个糟糕的主意。