jQuery基于页面URL添加类 [英] jQuery add class based on page URL
问题描述
我有我的想法是一个简单的问题,但我不能让它在我的生活中工作。
I have what I think is a simple question but I can't get it to work for the life of me.
全部我想做的是添加一些javascript到基于URL的主页容器中添加一个类的页面。
All I want to do is add some javascript to the page that adds a class to the main page container based on the URL.
假设我在root.com有一个网站和以下html结构(松散地):
Let's say I have a site at root.com and the following html structure (loosely speaking):
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<div id="main" class="wrapper">
Blah, blah, blah
</body>
</html>
我想要做的是一个脚本,如果页面= / technology,它向主div添加一个类。所以现在的div看起来像:
What I want to do is a script that, if the page = (for example) root.com/technology, it adds a class to the main div. So the div would now look like:
<div id="main" class="wrapper tech">
我已经加载jquery,所以我想这样做。
I've loaded jquery, so I'd like to do it that way.
推荐答案
您可以使用 window.location
获取当前URL,然后切换
You can use window.location
to get the current URL, and then switch based on that:
$(function() {
var loc = window.location.href; // returns the full URL
if(/technology/.test(loc)) {
$('#main').addClass('tech');
}
});
这使用正则表达式来查看URL是否包含特定的短语(值得注意的是:<$ c $元素
This uses a regular expression to see if the URL contains a particular phrase (notably: technology
), and if so, adds a class to the #main
element.
这篇关于jQuery基于页面URL添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!