【问题标题】:How to add body class to front page & an internal page using jQuery?如何使用 jQuery 将正文类添加到首页和内部页面?
【发布时间】:2017-01-09 20:51:36
【问题描述】:

下面的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 在同一功能中完成完全相同的事情。我该怎么做?

【问题讨论】:

  • 您能否提供进一步的说明 - 您还尝试附加附加类的什么元素?
  • @aphextwix 我想​​在<body> HTML 元素中添加一个full 类。
  • 看我的回答。我相信你正在寻找那个。

标签: javascript jquery function href


【解决方案1】:

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

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

【讨论】:

  • @LizBanach 很高兴为您服务!
【解决方案2】:

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

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

在您的情况下进一步添加。我会,使用window.location.pathname

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

【讨论】:

  • 这对我有用。我的最终代码是:// add full class to sign in page body for bg image $(function() { var loc = window.location.pathname; // returns the pathname if(/signin/.test(loc)) { $('body').addClass('full'); } if(/^\/$/.test(loc)) { $('body').addClass('full'); } });
猜你喜欢
  • 1970-01-01
  • 2021-11-05
  • 1970-01-01
  • 2011-06-01
  • 2017-10-08
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
  • 2012-08-26
相关资源
最近更新 更多