1. 程式人生 > >js獲取url中"?"後面的字串

js獲取url中"?"後面的字串

有2個頁面

A.html    

<a href="b.html?index=1">美食</a>
<a href="b.html?index=2">水果</a>
 <a href="b.html?index=3">衣服</a>

B.html

<p class="active" index="1">美食頁面</p>

<p index="2">水果頁面</p>

<p index="3">衣服頁面</p>

function GetRequest() {
                  var url = location.search; //獲取url中"?"符後的字串  這邊獲取到的就是 ?index=2
                  var theRequest = new Object();
                  if (url.indexOf("?") != -1) {

                      var str = url.substr(1);   //這邊得到的str  就是index=2

                          strs = str.split("&");    //這邊是可能並列引數的情況

                      for ( var i = 0; i < strs.length; i++) {
                          theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
                      }
                  }
                  return theRequest;
              }
        $("p").each(function(index,ele){
         var Request=GetRequest();
         var indexId=Request["index"];
         var op=$("p").eq(index).attr("index");
              if(indexId==op){
               $("p").removeClass("active")
               $("p").eq(index).addClass("active") 
             }
    })