大家肯定遇到了过这个问题,当你点击a标签的时候,想要给a标签,加上高亮选中的样式,可是页面刷新无法保存样式,那怎么办呢?我提供一种方法:循环a的链接,然后与location.href去比对,如果相同,或包含有同样字符串序列,则添加。
代码如下:
var url = window.location.href;
$("a").each(function () {
if (returnUrl($(this).attr("href")) == returnUrl(url)) {
console.log($(this));
$(this).addClass("selected");
}
});
//以下为截取url的方法
function returnUrl(href) {
var number = href.lastIndexOf("/");
return href.substring(number + 1);
}
不一定非得用lastIndexOf()
方法,还可以用substring()、substr()
- lastIndexOf() 方法可返回一个指定的字符串值最后出现的位置,在一个字符串中的指定位置从后向前搜索。
- substring() 方法用于提取字符串中介于两个指定下标之间的字符。
- substr() 方法可在字符串中抽取从 start 下标开始的指定数目的字符
或者直接:
$("a").each(function () {
var a_href = window.location.pathname;
if ($(this).attr("href") == a_href) {
console.log(123);
$(this).addClass("selected");
}
});
因为我的a标签是这样的:
<a th:href="@{'/user/news/'+${newsList.pageNum}+'/2/0'}"></a>
遍历出来等同于:
<a th:href=/user/news/0/1/0}"></a>
所以我用的是 window.location.pathname这个属性。