0

我有一个脚本可以根据 url 切换样式表。

必须这样做,因为该站点使用 smarty 模板,我不想更改核心文件或核心 css。

现在我必须添加每个单独页面的 URL 路径名。页面越多,这就越不切实际。

例如,而不是/ojs/index.php/index/user/registerand/ojs/index.php/index/user/profile我想调用/ojs/index.php/index/user/*so 那么下面的所有页面/user/都将应用样式表。

做这个的最好方式是什么?我看过几个类似的帖子,但不完全是我需要的。

var loc = window.location;
var currentURL = loc.pathname;

if (currentURL=='/ojs/index.php/index' || currentURL=='/ojs/' ||  currentURL=='/ojs/index.php/index/about' || currentURL=='/ojs/index.php/index/user/register' || currentURL=='/ojs/index.php/index/user/profile' || currentURL=='/ojs/index.php/index/admin/' || currentURL=='/ojs/index.php/index/admin/auth')

loadjscssfile("/ojs/plugins/themes/main-theme/main-theme.css", "css")
4

1 回答 1

0

您可以使用正则表达式

// unless you were using loc for something else, there is no need to store it,
// just chain to get the pathname
var currentURL = window.location.pathname,
    // create a regular expression that will match all pages under user
    usersPattern = new RegExp('^/ojs/index\.php/index/user/.*');

if (usersPattern.test(currentURL)) {
    loadjscssfile("/ojs/plugins/themes/main-theme/main-theme.css", "css")
}

与正则表达式一样,您需要小心您正在做的事情以使其正确。以下是此表达式如何工作的简短说明:

  • ^告诉它仅在字符串以/ojs/等开头时才匹配
  • 中间\.转义 the .,告诉它.inindex.php是一个字面点
  • 最后.的将匹配任何字符
  • 以下*.匹配前一个字符的 0 个或多个实例(在这种情况下为任何字符)

我使用构造函数创建了这个正则表达式RegExp,但也可以使用正则表达式文字来完成。一般来说,使用文字是一个更好的主意,但在这种情况下,我使用了构造函数,因为因为它需要一个字符串作为参数,所以我不必转义/模式中的字符。如果我们用文字来做,而不是这样:

usersPattern = new RegExp('^/ojs/index\.php/index/user/.*');

它看起来像这样:

usersPattern = /^\/ojs\/index\.php\/index\/user\/.*/;

不需要逃避那些/使它更具可读性。

于 2013-03-13T05:33:13.777 回答