【发布时间】:2016-06-23 10:12:15
【问题描述】:
这是我的代码
HTML
<div id="header-content" class="header-content">...</div>
jQuery
$( document ).ready(function() {
var loc = window.location.href; // returns the full URL
if(/$/.test(loc)) { // If Empty or if just home URL
$('#header-content').addClass('home-page');
//Remove All Other Classes
$('#header-content').removeClass('start-here');
$('#header-content').removeClass('work-with-me');
}
if(/start-here$/.test(loc)) { // if page = root/start-here/
$('#header-content').addClass('start-here');
//Remove All Other Classes
$('#header-content').removeClass('home-page');
$('#header-content').removeClass('work-with-me');
}
if(/work-with-me$/.test(loc)) { // if page = root/work-with-me/
$('#header-content').addClass('work-with-me');
//Remove All Other Classes
$('#header-content').removeClass('home-page');
$('#header-content').removeClass('start-here');
}
});
网址示例: http://www.somedomain.com/the-page/
我想做的是让脚本识别 url 中的文本“the-page”,如果匹配则分配类。正如您在我的示例 jquery 代码中看到的那样,我正在尝试将类分配给主页、从这里开始的页面和与我一起工作的页面。
我不确定如何修改上面的 Jquery,以便它可以使用 URL 示例格式。
以及我如何检测它是否是索引页面并且 URL 看起来像这样:http://www.somedomain.com/ 最后没有页面名称?
【问题讨论】:
-
如果我使用一个文件名,比如 page.php 并将其放在像这样的代码中
if(/start-here.php$/.test(loc)) { // if page = root/start-here/它将可以正常工作。最后使用 .php ,它可以与我构建的静态站点一起使用,但正如我所说,它无法与目录类型页面名称一起使用。 -
首先,
/$/.test(...)将适用于 any 字符串,因为所有字符串都有一个结尾。 -
我不知道你是什么意思克劳德。我在这方面有点新手。我不明白为什么我不能只添加一个“/”并删除 .php 并让它使用 URL 格式 (somedomain.com/page-name)
-
基本上我想做的是在页面加载时让脚本检查页面是否包含在 / 中的名称。所以我希望它使用两个正斜杠来查找“/page-name/”。如果它与分配的类匹配。
标签: javascript jquery