繁体   English   中英

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

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

下面的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');
  }
});

我想在首页/首页上完成完全相同的操作,或者在同一功能内完成/ URL。 我该怎么做呢?

正则表达式很慢。 更快的方法:

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

使用适当的正则表达式。 /^\\/$/在您的情况下。

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

根据您的情况进一步添加。 我会使用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