javascript如何修改url地址的引數

admin發表於2017-03-28

通常情況下都是獲取url傳遞的引數,這裡不多介紹了,可以參閱下面的文章。

獲取引數可以參閱js獲取url連結中的引數章節。下面就通過程式碼例項介紹一下如何修改url傳遞的引數。

程式碼例項如下:

[JavaScript] 純文字檢視 複製程式碼
function addToUrl(obj){ 
  var aprotocol = location.protocol; 
  var ahost = location.host; 
  var apath = location.pathname; 
  var asearch = location.search; 
  var ahash = location.hash; 
  var result = ''; 
     
  var joinObj = function(joinObj_obj){ 
    var result = ''; 
    for(var prop in joinObj_obj){ 
      result += prop + '=' + joinObj_obj[prop]; 
    } 
    return result; 
  }; 
  var splitSearchToObj = function(str){ 
    var resObj = {}; 
    var arr = str.split('&'); 
    for(var index = 0; index < arr.length; index++){ 
      resObj[arr[0]] = arr[1]; 
    } 
    return resObj; 
  }; 
  var existObjKey = function(existObjKey_obj, str){ 
    for(var prop in existObjKey_obj){ 
      if(prop == str){ 
        return true; 
      } 
    } 
    return false; 
  }; 
  var objExtend = function(obj1, obj2){ 
    var result = {}; 
    for(var prop in obj1){ 
      if(existObjKey(obj2, prop)){ 
        result[prop] = obj2[prop]; 
      }
          else{ 
        result[prop] = obj1[prop]; 
      } 
    } 
  }; 
  if(asearch == ''){ 
    result = aprotocol + '//' + ahost + apath + '?' + joinObj(obj) + ahash; 
  }
  else{ 
    var oldSearchObj = splitSearchToObj(asearch.substr(1)); 
    result = aprotocol + '//' + ahost + apath + joinObj(objExtend(oldSearchObj, obj)) + ahash; 
  } 
  return result; 
} 
console.log(addToUrl({'antzone':'螞蟻部落'}));

相關文章