如果body标签包含层次url,如何在标签上添加类



这可能是一个简单的问题。如果url是分层的,我如何将类添加到我的body标记中?

例如:我有一个网址:

/coding/product/business-account/

我只想在product下的所有子URL中添加一个类。

我使用的是这个脚本代码,但我认为regex只得到了它上面的第一个url路径。有什么调整可以只在/coding/product/url下添加类吗?

<script type="text/javascript">
// jQuery is passed to the ready function as a parameter, so we alias it with $
// This will work for you even with wikispaces
jQuery(function($){
var loc = window.location.pathname.match(/^/?(w+)b/);
console.log(loc);
if(loc) $(document.body).addClass(loc[1].toLowerCase());
});
</script>

let regex = /(?<=/product/)(.*)/;
let loc = regex.test(`/coding/product/business-account/`);  //regex.test(window.location.pathname)
console.log('url matched: ' + loc)
if(loc) {
//add class to element
}

最新更新