1

我在下面有这个代码工作,除了它只在 URL 是“domain/dev”而不是“domain/dev/”和尾部斜杠时工作。我对 JS 语法不是很熟悉,所以不知道如何更正。我尝试了不同的变体,添加了一个条件语句,但斜线似乎破坏了代码。

$(function() {
    var loc = window.location.href;
  if(/dev/.test(loc)) {
    var visited = 'visited';
    if($.cookies.get(visited) === null){
        $('#career-home').addClass('visited')
        $.cookies.set('visited', 'visited')
        console.log("addClass")
    }else{
        $('#career-home').removeClass('visited')
        console.log("removeClass")
    }
  }
  console.log(window.location.pathname);
});
4

2 回答 2

0

我能够使用此代码实现我所需要的(检查 cookie 是否存在,如果存在,则添加几个类,如果不存在,则添加一个类)

$(document).ready(function() {
    var pathArray = window.location.pathname.split( '/' );
    var cookieName = pathArray[2];
    var loc = window.location.pathname;
    if($.cookies.get(cookieName) === null) {
        $.cookies.set(cookieName, 'visited');
        $('#' + cookieName).addClass('current');
        setTimeout(function(){
            $('#' + cookieName).addClass('visited')
            console.log("addClass 'visited' to #" + cookieName)
        },5000);
        console.log("Set cookie = " + cookieName)
        console.log("addClass 'current' to #" + cookieName)
    } else {
        console.log(cookieName + " cookie value = " + $.cookies.get(cookieName))        
    }
    if(/dev/.test(loc)) {
        $('#' + cookieName).addClass('current');
    }       
});
于 2012-09-20T15:43:00.403 回答
0

这可能是一个黑客,但它应该工作

var loc = window.location.href;
    if(loc.substring(loc.length-1,loc.length) == '/'){
       loc = loc.substring(0,loc.length-1);}
于 2012-09-19T00:10:14.510 回答