2013-03-14 42 views
-2

我需要包含(通過Javascript)不同的內容,具體取決於從url捕獲的主要類別。使用Javascript確定URL中的/ category/

該網站佈局,像這樣:

http://example.com/Category/Arts/Other/Sub/Categories/

http://example.com/Category/News/Other/Sub/Categories/

http://example.com/Category/Sports/Other/Sub/Categories/

http://example.com/Category/Business_And_Finance/Other/Sub/Categories/

以上不同的主要類別有:

藝術,新聞,體育和Business_And_Finance

什麼是JavaScript來實現這一目標的最佳途徑。 我需要的可能看起來像下面,

if (category = Arts) { 
    alert("Arts"); 
}else if (category = News) { 
    alert("News"); 
}... 

預先感謝您。

回答

0

拆分放在location.href然後做適當的變量開關。因此,舉例來說:

var url = document.location.href, 
    split = url.split("/"); 

/* 
    Split will resemble something like this: 
    ["http:", "", "example.com", "Category", "Arts", "Other", "Sub", "Categories", ""] 

    So, you'll find the bit you're interested in at the 4th element in the array 
*/ 
switch(split[4]){ 
    case "Arts": 
    alert("I do say old chap"); 
    break; 

    case "News": 
    alert("Anything interesting on?"); 
    break; 

    default: 
    alert("I have no idea what page you're on :O!"); 
} 
+0

謝謝你的答案,這正是我需要的。並感謝所有在下面回答的人。大多數答案似乎都使​​用了相同的'url.split'思路。謝謝大家。 – Yallaa 2013-03-14 18:19:35

0

您可以訪問當前的URL這樣

document.location.href 

你可以做一個

if ( document.location.href.indexOf("categoryYouWant")>-1){ 
    //whatever you want 
} 

,但你應該做一個正則表達式

category=document.location.href.match(/example\.com\/(\w+)\//i)[1]; 
0
var url = window.location.href; 

var category = url.split('Category/')[1].split('/')[0]; 

if (category === 'Arts') { 
    alert("Arts"); 
}else if (category === 'News') { 
    alert("News"); 
} 
0

我做了這個例子:

<!DOCTYPE html> 
    <html> 

    <head> 
     <meta charset="utf-8"/> 
     <meta name="viewport" content="width=device-width, initial-scale=1"/> 

     <script type="text/javascript"> 
     function determine(url) 
     { 
      var myArray = url.split('/'); 
      if(myArray[4] == "News") 
      alert(myArray[4]); 

     } 

     </script> 
    </head> 

    <body> 

     <div>  
      <a href="" onclick="determine('http://example.com/Category/News/Other/Sub/Categories/')">http://example.com/Category/News/Other/Sub/Categories/</a>  
     </div> 

    </body> 
    </html> 

Saludos;)

相關問題