显示特定URL路径的div

我有一个网站,我需要为网站中的每个独特页面(大约25页)提供特定的标题div显示。 我已经创建了一组变量和一个非常长的if语句(下面简化 – 但运行大约25 if语句深)来运行该函数。 该function很有效,除了我有大约8个页面无法正常运行的问题。

问题:有没有比run-on if语句更好的方法来实现它?

基本代码:

var landing = "/home"; var information = "/information"; var bell = "/information/bell"; $(function(){ if (location.pathname.search(landing)!=-1){ $('.landing').show(); } else { if (location.pathname.search(information)!=-1){ $('.information').show(); } else { if (location.pathname.search(bell)!=-1){ $('.bell').show(); } else { $('.landing').show(); } } } });

您可以创建一系列routes

 var routes = { "landing": { "classname": ".landing", "pathname": /^\/home/ }, "information": { "classname": ".information", "pathname": /^\/information/ }, ... }; 

 $(function(){ for(route in routes){ if(routes.hasOwnProperty(route)){ if(window.location.pathname.match(routes[route].pathname) != -1) { $(routes[route].classname).show(); } } } }); 

注意route.pathname是正则表达式。 前缀^字符表示路径名需要以给定字符串开头。