使用 JavaScript 将 类 添加到 'body'

Adding classes to 'body' with JavaScript

我正在尝试将 类 添加到某些页面的 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');
}