1

我需要包含(通过 Javascript)不同的内容,具体取决于从 url 捕获的主要类别。

该网站的布局如下:

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/

上述不同的主要类别是:

艺术、新闻、体育和商业_And_Finance

在javascript中完成此操作的最佳方法是什么。我需要的可能如下所示,

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

先感谢您。

4

4 回答 4

1

拆分 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!");
}
于 2013-03-14T17:41:54.380 回答
0

您可以像这样访问当前网址

document.location.href

你可以做一个

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

但你应该做一个正则表达式

category=document.location.href.match(/example\.com\/(\w+)\//i)[1];
于 2013-03-14T17:41:19.677 回答
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");
}
于 2013-03-14T17:42:18.527 回答
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>

萨卢多斯 ;)

于 2013-03-14T17:46:53.420 回答