[英]Add class to <body> if url has more strings
我如何检测URL是否包含更多字符串并添加一个类,基本上我想添加一个类(如果是主页或内部页)
例如:如果网址为:正文中的https://example.com =>,请添加“首页”;如果网址为: https : //example.com/2018/04/test.html或.com之后的任何内容=>在正文中添加类“内页”
$(document).ready(function() {
if(url.indexOf('example.com') > -1){
$("body").addClass("home-page");
}
});
对于内部不起作用
您的答案的问题是,只要URL包含“ example.com”,它将返回true。 因此,您可能需要检查路径名:
document.body.setAttribute("class", (location.pathname.length <= 1 ? "home-page" : "inner-page")) console.log(document.body.className); //returns "inner-page"
也许您可以使用document.location.pathname
来确定要分配的类,如下所示:
$(document).ready(function() {
var url = document.location.pathname;
if(url === '/'){
$("body").addClass("home-page");
}
else {
$("body").addClass("inner-page");
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.