獲取Url中參數的方法

一般使用框架的話是可以很快獲取到url的參數

但是如果要手寫一個的話就需要封裝一個方法來

function params() {
  const search = window.location.search;  //window.location.search會返回url中包含?及其之後的字符串
  search = search.substr(1, search.length); //截取?後的字符串
  const res = {};
  if (!search) return res;
  search.split('&').map(item => {
    const [key, value] = item.split('=');
    res[key] = decodeURIComponent(value);
  });
  return res;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章