[英]Add class to <body> if url has more strings
how can i detect if URL has more strings and add an class basically i want add a class if is home page or if is Inner Page 我如何检测URL是否包含更多字符串并添加一个类,基本上我想添加一个类(如果是主页或内部页)
example: if the url is: https://example.com => in body add "home-page" and if the url is: https://example.com/2018/04/test.html or anything after .com => in body add class "inner-page" 例如:如果网址为:正文中的https://example.com =>,请添加“首页”;如果网址为: https : //example.com/2018/04/test.html或.com之后的任何内容=>在正文中添加类“内页”
$(document).ready(function() {
if(url.indexOf('example.com') > -1){
$("body").addClass("home-page");
}
});
for inners is not working 对于内部不起作用
The problem with your answer is that it will return true as long as the url contains "example.com". 您的答案的问题是,只要URL包含“ example.com”,它将返回true。 Thus you might want to check for the pathname instead :
因此,您可能需要检查路径名:
document.body.setAttribute("class", (location.pathname.length <= 1 ? "home-page" : "inner-page")) console.log(document.body.className); //returns "inner-page"
Perhaps you could user document.location.pathname
to determine which class to assign like so: 也许您可以使用
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.