开发者

How Can I Add a Class to the Body Tag using jQuery?

Let me clarify my question, and the solution I'm looking for. I'm using wikispaces.com, and I would like to dynamically add a unique body class for every page using jQuery that somehow grabs the URL, and then inserts that unique body class that would be applied specifically and only for that page.

So, here's an example url from my wikispace...

http://wikithemes.wikispaces.com/Audio+Page

I'd like the jQuery to grab... let's say the first word after the .com/, which on this page would be开发者_运维百科 audio. So, the jQuery I need would apply the class audio to the body tag, like so...

<body class="audio">

In their documentation, any jQuery can be inserted since it is loaded by default. But they clarify in saying that instead of the $ sign used within jQuery, it will only work within wikispaces if you use the word jQuery instead. Like this...

jQuery(document).ready(function(){

I really appreciate any help you can give me on getting this to work. Thanks!


Not sure what your restrictions are in placing code. I would just put this in the <head> of your document and apply the class to the html element instead of body so you don't get a FOUS or "Flash of Unstyled Content". The class is "present" on the element almost immediately after the page loads, but before it displays if you do it this way:

<script type="text/javascript">
    var loc = window.location.pathname.match(/^\/?(\w+)\b/);
    // document.documentElement is the html element, this adds the class
    if(loc) document.documentElement.className += " " + loc[1].toLowerCase();
</script>

If you really want to use jQuery:

<script type="text/javascript">
    // jQuery is passed to the ready function as a parameter, so we alias it with $
    // This will work for you even with wikispaces
    jQuery(function($){
        var loc = window.location.pathname.match(/^\/?(\w+)\b/);
        if(loc) $(document.body).addClass(loc[1].toLowerCase());
    });
</script>


Regular javascript:

jQuery(document).ready(function(){
    var urlPath = window.location.pathname;
    document.body.className = urlPath.match(/\/(.*?)(\+|$)/)[1].toLowerCase();

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜