如何使用javascript/jquery检查url,即使它们是尾随斜杠?
我有两个面板,其中有一个链接列表,用作博客的侧边栏。如果其中一个面板包含指向当前url的链接,它将展开 问题是,如果在当前url的末尾添加了一个尾随斜杠,它将不再工作。我如何才能做到这一点,使它的工作,无论是否有一个网址尾随斜杠 以下是我正在使用的当前代码:如何使用javascript/jquery检查url,即使它们是尾随斜杠?,jquery,url,window,location,addclass,Jquery,Url,Window,Location,Addclass,我有两个面板,其中有一个链接列表,用作博客的侧边栏。如果其中一个面板包含指向当前url的链接,它将展开 问题是,如果在当前url的末尾添加了一个尾随斜杠,它将不再工作。我如何才能做到这一点,使它的工作,无论是否有一个网址尾随斜杠 以下是我正在使用的当前代码: jQuery('.list-group-item a[href$="' + window.location.pathname + '"]').addClass("active").parents('.panel .panel-heading
jQuery('.list-group-item a[href$="' + window.location.pathname + '"]').addClass("active").parents('.panel .panel-heading a').collapse('show');
下面是一个活生生的例子:
但如果您访问此项,它将不起作用(请注意后面的斜杠):
您只需检查最后一个字符是否为“/”并将其删除: 大概是这样的:
jQuery(
var pathName = window.location.pathname;
//check if last character is /
if (pathName[pathName.length - 1] == "/")
{
pathName = pathName.substring(0, pathName.length - 1);
}
'.list-group-item a[href$="' + pathName +'"]').addClass("active")
.parents('.panel .panel-heading a').collapse('show');