使用Jquery更改url时将类添加到body?

时间:2017-03-13 16:03:20

标签: javascript php jquery css

我在ajax中使用了一个插件来过滤我网站的某些产品。 网址会在不重新加载页面的情况下更改。

我需要识别网址,拆分单词并将这些类添加到正文中。

E.G:我过滤了一些产品,然后我的网址更改为https://website.com/size=big/color=yellow,green,dark-red 所以,这个类将添加到body:size big color yellow green dark-red

我有这个代码,但我不知道如何使它工作。

$(window).on('hashchange', function(e){
       $('body'). 
});

感谢。

1 个答案:

答案 0 :(得分:1)

更新:根据我的回答中的评论主题,您似乎真的想将查询字符串值转换为css类名。

您可以使用window.location.search访问所有查询字符串参数。

function updateBodyClasses() {

  var classNames = [];

  // Use `.split()` to separate each key/value pair in the query by `&`
  window.location.search.split('&')
    // and loop over the results
    .forEach(function(c) {

      // Now split each pair by '='
      var pair = c.split['='];

      // Add the value to the left of the '=' 
      if (pair.length > 0) {
        classNames.push(pair[0]);

        // if there are values on the right of the '='...
        if (pair.length > 1) {

          // ... split them by ',' and loop through them
          pair[1].split(',').forEach(function(t) {
            classNames.push(t);
          });      
        }
      }
    });

    // Now append those classNames to the body
    $('body').addClass(classNames.join(' '));
}

// If your ajax plugin modifies the url via HTML5 history api...
$(window).on('popstate', updateBodyClasses);


// Update classes on page load
$(window).on('load', updateBodyClasses);

// If the ajax plugin modifies the url using window.location.replace()
// you'll need to check on an interval whether things have changed
// and update accordingly. the following example does this every 1000 milliseconds (or every second)

setInterval(updateBodyClasses, 1000);