2017-07-15 137 views

回答

0

返回整个URL让我们假设您的网址是: http://localhost/test/test.html?q=mySearchString#do/users/view

以下功能将提取位置,路径,散列的queryString,得到的参数和来自此网址的细分。

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

alert(suPlayWithLocation('path',0)); //返回http://localhost/test/test.html

alert(suPlayWithLocation('hash',0)); //返回do/users/view

alert(suPlayWithLocation('queryString',0)); //返回q = mySearchString

alert(suPlayWithLocation('get','q')); //返回mySearchString

alert(suPlayWithLocation('segment','2')); //返回用户

+0

为什么你需要这第一个参数?你不能像* parser.get(“q”)*一样实现它吗? –

1

的今天最简单的将是一个地图查询:

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

所以,你可以这样做:

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

这只是实现了查询参数(您的问题关于)。

相关问题