2016-09-14 75 views
0

我試圖將類添加到某些頁面的body。除了第2,3,4條if語句之外,所有類都會被添加,如下所示。我想也許這是因爲if語句的順序?我不確定。有人可以幫我嗎?使用JavaScript將類添加到「body」

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'); 
    } 

回答

2

訂單是問題。 ?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'); 
} 
相關問題