Get the parameters in the url

Encapsulate a method
We know that the parameters in the url are displayed in this form
?id=123&name=tom&age=13...
The first type: the basic usage is divided by strings

所以。来吧展示
function getParams(key) {
	var result = {} // 定义一个全局的对象
	var str = window.location.search;
	if(str.startsWith('?')) { // 判断str以?开头的
		var strParams  = str.split('?')[1];
		var arrParams = strParams.split('&');
		//然后进行for循环,这里直接用了forEach
		arrParams.forEach((item) => {
			var temKey = item.split('=')[0];
			var temVal = item.split('=')[1];
			result[temKey] = temVal
		})
	}
	return result[key]
}
或者
getUrlParameter: function(field) {
    //获取Url 参数     
    var GET = {};
    var canshu=window.location.hash.split("?")[1]==undefined?'':window.location.hash.split("?")[1];
    if(canshu!=''){
      var strarr = canshu.split("&");
      for(i=0;i<strarr.length;i++){
        var xx = strarr[i];
        var mykey = xx.split('=')[0];
        var myvalue = xx.split('=')[1];
        GET[mykey] = myvalue;
      }
    }
    return GET[field];
  }

The second: URLSearchParams
This method is a built-in object of JS, which can map out search query conditions.
Using the get method, you can get the specified parameters

function get ParamsNew(key) {
	var temData = new URLSearchParams(window.location.search);
	return temData.get(key)
}

insert image description here
End
Extension
When we modify the data, suppose we want to get the ID to display

var id = getParamsNew('id');
if(id){
	// 有id的时候就要加载数据
	loadData(); // 把需要修改的数据填充在表单里面
};
// 方法
function loadData() {
	var strPeople = localStorage.getItem('myStudent'); // 我们从localStorage中取值
	var people = [];
	if(strPerple) {
		people= JSON.parse(strPeople);
	}
	// 如果箭头函数只有一行的话,可以不写return
	// 我们利用数组中的find方法,查找复核条件的数据
	var person = people.find((item) =>{
		item.id == id // 查找符合条件的项
	})
	// 进行赋值操作
	XXname.value = person.name;
	XXage.value = person.age;
	.....// 这样就赋值成功了
}

In this way, you can edit and display it, but you should pay attention to whether it is a new addition and a modification. If it is in one piece, you must add a judgment condition when saving.
You can read this article https://blog.csdn.net/lzfengquan/article /details/118605300?spm=1001.2014.3001.5501

Guess you like

Origin blog.csdn.net/lzfengquan/article/details/122964580