2017-07-15 13 views

答えて

0

私たちはあなたのURLがあるとしましょうを使用して返すことができます知っている http://localhost/test/test.html?q=mySearchString#do/users/view

このURLのセグメント

function suPlayWithLocation(doWhat, arg) { 
       //doWhat options: location, path, hash, queryString, get and segment 
       //Pass arg as 0 (zero) for location, path, hash and queryString 
       //Pass arg as the get parameter name for queryString 
       //Pass arg as the segment number for segment 

       //Get location 
       if (doWhat == 'location') { 
        if (window.location) { 
         return window.location; 
        } 
       } 
       //Get path 
       if (doWhat == 'path') { 
        if (window.location.pathname) { 
         return window.location.pathname; 
        } 
       } 
       //Get hasg 
       if (doWhat == 'hash') { 
        if (window.location.hash) { 
         return window.location.hash.substr(1); 
        } 
       } 
       //Get query string 
       if (doWhat == 'queryString') { 
        if (window.location.search) { 
         return window.location.search.substr(1); 
        } 
       } 
       //Get the value of get parameter 
       if (doWhat == 'get') { 
        if (window.location.search) { 
         var result = null, 
           tmp = []; 
         var items = location.search.substr(1).split("&"); 
         for (var index = 0; index < items.length; index++) { 
          tmp = items[index].split("="); 
          if (tmp[0] === arg) 
           result = decodeURIComponent(tmp[1]); 
         } 
         return result; 
        } 
       } 
       //Get segment value 
       if (doWhat == 'segment') { 
        if (window.location.hash) { 
         arg = arg - 1; 
         segment = window.location.hash.substr(1).split('/'); 
         return segment[arg]; 
        } 
       } 
      } 

alert(suPlayWithLocation( 'location'、0)); //返品http://localhost/test/test.html?q=mySearchString#do/users/view

アラート(suPlayWithLocation( 'path'、0)); //返品http://localhost/test/test.html

アラート(suPlayWithLocation( 'hash'、0)); //返すdo/users/view

alert(suPlayWithLocation( 'queryString'、0)); //戻り値q = mySearchString

アラート(suPlayWithLocation( 'get'、 'q')); //返品mySearchString

アラート(suPlayWithLocation( 'segment'、 '2')); //今日は、クエリの地図になり、最も簡単なユーザーに

+0

なぜこの最初の引数が必要ですか? * parser.get( "q")*のように実装できませんでしたか? –

1

を返します:

console.log(query.get("q"))//mySearchString 

これはちょうどあなたの質問だったクエリパラメータを(実装していますので、あなただけ行うことができます

var query=new Map(location.href.split("#")[0].split("?")[1].split("&").map(el=>el.split("="))); 

は、約)。

関連する問題