2015-09-04 37 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

對不起,我發佈了錯誤的代碼,請你再檢查一次嗎?謝謝! –