Определите /категорию/ в URL-адресе с помощью Javascript


person Yallaa    schedule 14.03.2013    source источник


Ответы (3)


Разделите 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!");
}
person Doug    schedule 14.03.2013
comment
Спасибо за ваш ответ, это то, что мне было нужно. И спасибо всем ответившим ниже. В большинстве ответов используется одна и та же идея url.split. Спасибо всем. - person Yallaa; 14.03.2013

вы можете получить доступ к текущему URL-адресу, как это

document.location.href

ты мог бы сделать

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

но вы должны сделать регулярное выражение

category=document.location.href.match(/example\.com\/(\w+)\//i)[1];
person japrescott    schedule 14.03.2013

Я сделал этот пример:

<!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>

Салюдос ;)

person Hackerman    schedule 14.03.2013