0

I am trying to add a class to the body depending on the url querystring (or hash if thats easier)

If you go to http://www.here.com?myclass I want to page to change the class of the body to: <body class="myclass">

This is the closest I got using a hash:

$(document).ready(function() {

    var url=document.URL.split('#')[1];
    if(url == undefined){
        url = '';
    }

    if(url != ''){
        $(document.body).addClass('myclass');
    }
});
4

3 回答 3

0

您的代码很接近:

var url=document.location

或者

var url=document.location.hash
于 2013-07-24T20:26:27.740 回答
0

当我能在这里找到答案时,我总是喜欢它,所以我会把它粘贴进去。

那里的这段代码是 url http://www.domain.com#中的一个散列#将一个“myclass”类添加到 body 标记中。请注意,它添加了不替换的类。

$(文档).ready(函数() {

var url=document.location.hash;
if(url != ''){
    $(document.body).addClass('myclass');
}

});

于 2013-07-25T12:43:31.837 回答
0

由于您知道要添加类的查询字符串,因此应该可以:

$(function() {
   if (document.location.href.indexOf('?myclass') > -1 ) {
     $('body').addClass('myclass');
   } 
});

使用 > -1 或 >= 0 搜索字符串以避免错误。

于 2015-10-01T22:06:35.717 回答