简体   繁体   English

如何使用jQuery将正文类添加到首页和内部页面?

[英]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. 下面的jQuery函数可以正常工作,并根据URL向/signin/页面上的<body> HTML元素添加full类。

// 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. 我想在首页/首页上完成完全相同的操作,或者在同一功能内完成/ URL。 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 我会使用window.location.pathname

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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