简体   繁体   中英

How to add body class to front page & an internal page using jQuery?

The jQuery function below works properly, and adds a full class to the <body> HTML element on the /signin/ page based on the URL.

// add full class to sign in page body based on url

$(function() {
    var loc = window.location.href; // returns the full URL
    if(/signin/.test(loc)) {
    $('body').addClass('full');
  }
});

I want to accomplish the exact same thing on the front/home page, or / URL within this same function. How do I do this?

Regexes are slow. A faster way:

function() {
    var loc = window.location.pathname; // returns the pathname
    if(loc == '' || loc == '/') {
        $('body').addClass('full');
    }
});

Using an appropriate regex. /^\\/$/ in your case.

/^\/$/.test('/') // true
/^\/$/.test('/asdf')  //false

Further adding to it in your case. I would, use window.location.pathname

$(function() {
    var loc = window.location.pathname; // returns the pathname
    if(/^\/$/.test(loc)) {
        $('body').addClass('full');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM