如何给一个网页传递参数

⌚Time: 2024-04-14 15:19:00

👨‍💻Author: Jack Ge

通过链接给网页传递参数

<--传参 file=abc.txt-->
<a href="xxx.html?file=abc.txt">跳转</a>

网页内通过js脚本获取参数

// 创建URLSearchParams对象
const params = new URLSearchParams(window.location.search);
// 读取参数值“abc.txt”
const file = params.get('file'); 

多个参数传递使用&连接

<a href="xxx.html?file=abc.txt&name=sss">跳转</a>

判断是否有参数


const params = new URLSearchParams(window.location.search);
const file = params.get('file'); 
if(file.trim().length != 0){
    //有参数
}

localStorage传递参数

// 在第一个页面设置参数值
  localStorage.setItem("name", "张三");
  localStorage.setItem("age", "18");
  // 在第二个页面获取参数值
  var name = localStorage.getItem("name");
  var age = localStorage.getItem("age");