[英]JQuery changing class of element with id or class based on page url/name
这是我的代码
的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');
}
});
URL示例: http : //www.somedomain.com/the-page/
我想做的是让脚本在url中标识文本“ the-page”,如果匹配则分配类。 如您在示例jquery代码中所看到的,我试图将类分配给主页,“从这里开始”页面和“与我一起工作”页面。
我不确定如何修改上述Jquery,因此它可以与URL Example格式一起使用。
以及如何检测它是否是索引页面,URL是否看起来像这样: http : //www.somedomain.com/ ,末尾没有页面名称?
好吧,假设该域是已知的,则应该可以这样做:
//you'll of course want to get this via window.location.href instead:
var exLoc = "http://www.somedomain.com/the-page/";
var root = "somedomain.com";
var end = exLoc.slice(exLoc.lastIndexOf(root)+root.length);
//end is your "text" at the end of your domain (somedomain.com in this case)
使用您的示例,结果类似于:
$( document ).ready(function() {
var loc = window.location.href; // returns the full URL
var root = "somedomain.com";
var end = loc.slice(loc.lastIndexOf(root)+root.length);
if(end.length <= 0) { // 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(end === "/start-here/") { // 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(end === "/work-with-me/") { // 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');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.