简体   繁体   English

获取用户访问过的上一页URL,并使用jQuery将类添加到当前页面上的元素

[英]Get previous page URL a user has visited and add class to element on current page using jQuery

I need to get the previous page URL a user has visited and then apply an "active" class to an element on the current page using jQuery. 我需要获取用户访问过的上一个页面URL,然后使用jQuery将“活动”类应用于当前页面上的元素。

My website sells telephone numbers so if a user visits a page that sells 0800 numbers then goes to the shop page I want my 0800 anchor link to have an active class 我的网站出售电话号码,因此,如果用户访问出售0800号码的页面,然后转到商店页面,我希望我的0800定位链接具有有效的班级

Here is what I have... 这就是我所拥有的...

$("#range a").each(function () {
    if ($(this).attr("href") == document.referrer) {
        $(this).addClass("active");
    }
});

but the class isn't adding. 但是班级没有增加。 Is document.referrer the correct way to grab the previous URL? document.referrer是获取先前URL的正确方法吗?

Thanks 谢谢

Probably you're using relative paths in your links. 可能是您在链接中使用了相对路径。 document.referrer returns an absolute path. document.referrer返回绝对路径。 Note that # fragments can also be different among other things that can make the comparison return false. 请注意, #片段之间的差异也可能有所不同,这会使比较返回false。 Maybe you should parse document.referrer using the next trick to compare properly with your link href. 也许您应该使用下一个技巧来解析document.referrer ,以便与链接href进行正确比较。

https://gist.github.com/jlong/2428561 https://gist.github.com/jlong​​/2428561

So I used CBroe's method of Logging both values to the console, and checking to see if the expectation actually matched reality. 因此,我使用了CBroe的方法将两个值都记录到控制台中,并检查期望值是否与实际情况相符。 It turned out the URLs we're different so that's why I wasn't getting an expected result. 原来我们的URL不同,所以这就是为什么我没有得到预期的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM