使用 JavaScript 向'body'添加类



我试图将类添加到某些页面的body。除了下面标记的第二、第三和第四个if语句之外,所有的类都被添加。我想可能是因为if语句的顺序?我不确定。有人能帮我一下吗?

  if (window.location.href.match(//shop/?category/)) {
      jQuery('body').addClass('shop-category');
  } else if (window.location.href.match(//shop/?category=Chef/)) { //doesn't get added
      jQuery('body').addClass('shop-category-chef');
  } else if (window.location.href.match(//shop/?category=Tactical/)) { //doesn't get added
      jQuery('body').addClass('shop-category-tactical');
  } else if (window.location.href.match(//shop/?category=Tools/)) { //doesn't get added
      jQuery('body').addClass('shop-category-tools');
  } else if (window.location.href.match(new RegExp('/shop/.+')) ) {
      jQuery('body').addClass('shop-item');
  } else if (window.location.href.match('/shop/')) {
      jQuery('body').addClass('shop');
  }

顺序是个问题。?category?category=Chef之前匹配。只要改变顺序。

if (window.location.href.match(//shop/?category=Chef/)) {
  jQuery('body').addClass('shop-category-chef');
} else if (window.location.href.match(//shop/?category=Tactical/)) {
  jQuery('body').addClass('shop-category-tactical');
} else if (window.location.href.match(//shop/?category=Tools/)) {
  jQuery('body').addClass('shop-category-tools');
} else if (window.location.href.match(//shop/?category/)) {
  jQuery('body').addClass('shop-category');
} else if (window.location.href.match(new RegExp('/shop/.+'))) {
  jQuery('body').addClass('shop-item');
} else if (window.location.href.match('/shop/')) {
  jQuery('body').addClass('shop');
}

最新更新