添加 class 到 <body> 如果 url 有 /shop/

Add class to <body> if url has /shop/

我正在 SquareSpace 商店工作,不幸的是,没有 class 被添加到所有商店页面的正文中。我的意思是任何以 http://example.com/shop/

开头的页面

我想为所有以此 url 开头的页面正文添加一个 class,无论它是 http://example.com/shop/item1http://example.com/shop/category/category-name

我试过了,但是 class 没有被添加到 <body>

$(document).ready(function() {
    if(url.indexOf('/shop/') > -1){
        $("body").addClass("shop");
    }
});

我怎样才能完成这项工作?

$(document).ready(function() {
    if(window.location.href.match('example.com/shop')){
        $("body").addClass("shop");
    }
});

您可以使用 window.location.pathname,您的情况是 shop/index.html

$(document).ready(function() {
    if(window.location.pathname.match('shop')){
        $("body").addClass("shop");
    }
});

您可以使用普通 Javascript 例如

if (document.location.pathname.indexOf("/shop/") == 0) {
    document.body.className = "shop";
}

对于 indexOf,对于所有以 /shop/ 开头的路径名,它将 return 为真。如果是这样,它会将 Class shop 添加到 <body> 元素。

所以在每个以 shop 开头的 URL 上,body 得到一个 ID shop