Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

javascript - 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.

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.

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>

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">

I've loaded jquery, so I'd like to do it that way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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');
  }
});

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...