2015-09-04 46 views
1

[更新代码再次] 我有以下代码:的jQuery - 添加基于URL和无URL类

var header_url = window.location.href; 
if(/index/.test(header_url)||/home/.test(header_url)){ 
    $('#home').addClass('select'); 
} else if(/about/.test(header_url)) { 
    $('#about').addClass('select'); 
} else if(/contact/.test(header_url)) { 
    $('#contact').addClass('select'); 
} 

的代码的工作,当我点击他们:

http://example.com/index.html 
http://example.com/about.html 
http://example.com/contact.html 

但如果我想要添加另一个页面,请将其设置为默认主页,而不使用url,如下所示:

http://example.com 

我尝试添加代码但它不起作用:

else if(/.test(header_url)) { 
     $('#default').addClass('select'); 
    }  

任何人都可以帮忙吗?谢谢!在开关的情况下

+1

使用''中之开关default'情况下 – Tushar

+0

@Tushar对不起,我贴错码,可以请你再检查? –

+0

然后在末尾添加一个'else'并将其用于'default'的情况 – Tushar

回答

0

您尚未为上一个条件创建正确的表达式。尝试下面的代码

var header_url = 'http://example.com'; 
//var header_url = 'http://example.com/index.html'; 
//var header_url = 'http://example.com/about.html'; 
//var header_url = 'http://example.com/contact.html'; 
if(/index/.test(header_url)||/home/.test(header_url)){ 
    console.log('index'); 
} else if(/about/.test(header_url)) { 
    console.log('about'); 
} else if(/contact/.test(header_url)) { 
    console.log('contact'); 
} else if(/\//.test(header_url)) { 
    console.log('nothing'); 
} 

检查这个小提琴太http://jsfiddle.net/anandgh/k63f3a33/1/

1

您使用默认像

switch (window.location.pathname) { 
case '/index': 
$('#home').addClass('select'); 
break; 
case '/about': 
$('#about').addClass('select'); 
break; 
case '/contact': 
$('#contact').addClass('select'); 
break; 
default: 
$('#default').addClass('select'); 
break; 
} 

尝试。

+0

对不起,我发布了错误的代码,请你再检查一次吗?谢谢! –