簡體   English   中英

將課程添加到 <body> 如果url有更多字符串

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM