前端在html页面之间跳转与传值(js代码

本文详述了网页跳转的各种方法,包括window.location.href、window.open等,并深入探讨了参数传递的不同策略,如URL参数、cookie和localStorage。同时,提供了实际案例和常见问题的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

页面跳转方法如下;

方法一:

window.location.href="b.html";

方法二:

self.location="b.html";

方法三:

top.location="b.html";

方法四(返回上一个页面,这个应该不算,先放这):

window.history.back(-1);

问题的思考:

1.为什么给window.location和window.location.href赋值时一样的,都可以跳转?思考:location是location.href的简写,无论是访问还是赋值。从功能上,location等于location.href是它的一个属性。(这一怪异行为应该是为了兼容

2.给location赋值的时候,如果跳转的页面不是在同一个目录下,需要把完整的URL写上。如:当前location.href为https://www.ellar.com/,如果要跳转到https://www.xing.com/,就不能只是www.xing.com,必须把URL写完整。

通过window.location.open

如果是希望打开一个新页面,而不是改变当前页面,那么window.location.href就不行了,我们需要借助于window.location.open()来实现。

简单介绍一下window.open()函数,window.open()有三个参数,第一个参数要打开的页面的url,第二个参数是窗口目标,第三个参数是一个特定的字符串以及一个表示新页面是否取代浏览器历史集中当前加载页面的布尔值,通过只需要传递第一个参数。第二个参数还可以是”_blank”,”_self”,”_parent”,”_top”这样的特殊窗口名称,”_blank”打开新窗口,”_self”实现的效果同window.location.href.

例如:

<script>
    var index = "lemon";
    var url = "receive.html?index="+index;
    $("#more").click(function(){
        window.open(url)
    });
</script>

 在点击的时候,就会打开一个新页面,页面的url地址与上面相同。

由于浏览器的安全限制,有些浏览器在弹出窗口配置方面增加限制,大多数浏览器都内置有弹出窗口的屏蔽程序,因此,弹出窗口有可能被屏蔽,在弹出窗口被屏蔽时,需要考虑两种可能性,一种是浏览器内置的屏蔽程序阻止弹出窗口,那么 window.open()很可能返回Null,此时,只要监测这个返回的值就可以确定弹出窗口是否被屏蔽。

var newWin = window.open(url);
if(newWin == null){
    alert("弹窗被阻止");
}

另一种是浏览器扩展或其他程序阻止的弹出窗口,那么window.open()通常会抛出一个错误,因此,要像准确的检测弹出窗口是否被屏蔽,必须在检测返回值的同时,将window.open()封装在try-catch块中,上面的例子中可以写成如下形式:

    var blocked = false;
    try{
        var index = "lemon";
        var url = "receive.html?index="+index;
        $("#more").click(function(){
           var newWin = window.open(url);
           if(newWin == null){
               blocked = true;
           }
        });
    } catch(ex){
        block = true;
    }
    if(blocked){
        alert("弹出窗口被阻止");
    }    

 

页面传值的方法如下:

方法一:通过URL传参(?后面的参数)(把URL后面的参数解析为对象)

window.location.href="http://localhost:63342/test/receive.html?hid=lemon&seth=seth";

案例:

1、项目中经常会出现的一种情况,有一个列表,譬如案例列表,点击列表中的某一项跳转到详情页面。详情是根据所点击的某条记录生成的,因为案例和具体的详情页面,都是用户后期自行添加的,我们开始编写时,不可能穷尽。因此跳转页面时,需要传递一个参数过去,这样我们才能通过这个参数进行数据请求,然后根据后台返回的数据来生成页面。通过<a>标签跳转页面的方式,肯定是行不通的。

经常写form表单提交时,可以传递参数,如果使用表单,并将其隐藏起来,应该可以达到效果。另外window.location.hrefwindow.open也可以达到效果。

通过form表单传递参数

<!Doctype html>
<html lang="en">
    <head>
      <title>Document</title>
      <meta http-equiv="content-type" content="text/html;charset=utf-8" />
      <script type = "text/javascript" src = "jquery.js"></script> 
   <style>
   .form{position:relation}
.btn{position:absolute;left:10px;top:0px;width:120px;height:40px;opacity:0;cursor:pointer;}
.more{width:120px;height:40px}
   </style>
   </head>
 <body>
    <form name="form" method="get" action="receive.html" onsubmit="return foo()"class="form">
            <input type="hidden"  name="hid" value = "" index = "black"> 
            <input type="hidden"  name="ty" value = "" index = "aaa"> 
            <img class = "more" src = "tu.png" />
            <button type = "submit" class="btn">点击按钮1</button>
    </form>

    <form name="form" method="get" action="receive.html" onsubmit="return foo()" class="form">
            <input type="hidden"  name="hid" value = "" index = "red"> 
            <img class = "more" src = "main_jpg10.png" />
            <button type = "submit" class="btn">点击按钮2</button>
    </form>
    <form name="form" method="get" action="receive.html" onsubmit="return foo()" class="form">
            <input type="hidden"  name="hid" value = "" index = "blue"> 
            <img class = "more" src = "main_jpg10.png" />
            <button type = "submit" class="btn">点击按钮3</button>
    </form>
<script>
     function foo(){
       var fm=window.event.srcElement;
       fm.hid.value=$(fm.hid).attr("index");
       fm.ty.value=$(fm.ty).attr("index");
       return true;
     }
</script>
</body>
</html>

点击图片时,跳转至receive.html页面。页面的url变成

http://localhost:63342/test/receive.html?hid=lemon&seth=seth

此时我们想要的值已经传过来了,在对当前字符串进行分割

<script>
      //方法一:
       var el,elURL,url,para,result,arr;
       el = document.getElementById("p1");
       elURL= window.location.search;//获取get请求的参数 获取到数据,是以?传过来的值 “?hid=lemon&seth=seth”
       result={};//存储对象
       arr=[];
        //通过解析字符串,获取确定的数据。
        function paraURL(url){
          //从第二个字符开始截取,获取到第二个开始后面所有的字符
          //url=url.substr(1);或url=url.substring(1);同下面这个
          url= url.split("?")[1];//hid=lemon&seth=seth
          para =url.split("&");  //分割字符串  --> 产生字符串数组
          //遍历数组中的每一个元素
         for(var i=0;i<para.length;i++){
             arr = para[i].split('=');
             var name=arr[0];
             var value=arr[1];
//unescape加密
            //result[name]=unescape(value);

      result[name]=encodeURI(value); //解决中文乱码问题
             el.innerHTML += name+":"+result[name]+"\n";
         }
             /* 同上
               para.forEach(function(v){
                   arr=v.split("=");
                   var name=arr[0];
                   var value = arr[1];
                   result[name]=value;
               })
               return result;
            */
         return result;
        }
        paraURL(elURL);  
</script>

 输出结果:hid:lemon seth:seth

2.方法

/**
 * 获取指定的URL参数值
 * URL:http://www.baidu.com/index?name=aaa
 * 参数:paramName URL参数
 * 调用方法:getParam("name")
 * 返回值:aaa
 */
function getParam(paramName) {
    paramValue = "", isFound = !1;
    if (this.location.search.indexOf("?") == 0 && this.location.search.indexOf("=") > 1) {
        arrSource = decodeURI(this.location.search).substring(1, this.location.search.length).split("&"), i = 0;
        while (i < arrSource.length && !isFound) arrSource[i].indexOf("=") > 0 && arrSource[i].split("=")[0].toLowerCase() == paramName.toLowerCase() && (paramValue = arrSource[i].split("=")[1], isFound = !0), i++
    }
    return paramValue == "" && (paramValue = null), paramValue
}

特别注意:

在使用的过程中,发现在获取的参数中存在中文时,获取到的值是乱码的

解决办法:

将解码方式unscape换为decodeURI

原因:

浏览器会将url中的中文参数进行encodeURI编码,所以要通过js使用decodeURI进行解码

 

3.如果要获取seth的参数值

js代码

var obj={
    getQueryString:function(name){
      var reg=new RegExp("(^|$)" +name +"=([^&]*)(&|$)";
      var r = decodeURIComponent(window.location.search).substr(1).match(reg);
       if(r !=null) return unescape(r[2]);
 //return decodeURI(r[2]); //解决中文乱码问题

       return null;
    }

}
//或者


//var i = 1;
//var j = 2;
//用法(1) local.href = "xxx.html?id=1"
//用法(2) local.href = "xxx.html?id=" + i
//用法(3) local.href = "xxx.html?id=" + i "&j=" j
 
function getUrlParam(name) {
    //构造一个含有目标参数的正则表达式对象
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); 
    var r = window.location.search.substr(1).match(reg); //匹配目标参数
    if (r != null) {
        return unescape(r[2]);
 //return decodeURI(r[2]); //解决中文乱码问题
    } else {
        return null; //返回参数值
    }
}
//获取参数
getUrlParam(id)
getUrlParam(j)

使用

var target=obj.getQueryString('seth');
console.log(target);

 

方法二:cookie传参

在一个web项目中,会有大量的界面。有很多功能是必须要向后台发送请求才能实现的,而界面间传值可以减少不必要的、重复的发送请求操作,从而减轻后台的负担。

function setCookie(cname,cvalue,exdays){
    var  d= new Date();
    d.setTime(d.getTime()+(exdays*24*60*60*1000));
    var expres = "expires=" + d.toUTCString();
    document.cookie = cname +"=" + cvalue + ";" +expries;
}
function getCookie(cname){
   var name=cname+"=";
   var ca=document.cookies.split(';');
   for(var i=0; i<ca.lenght;i++){
     var c=ca[i];
     while(c.charAt(0)==''){
        c=c.substring(1);
      }
      if(c.indexOf(cname) == 0){
        return c.substring(name.length,c.length);
      }
   }
   return "";
}

使用cookie保存 

//原生写法:
//1.保存一条数据
document.cookie='name=abc';
document.cookie='age=18';
//2.获取所有数据
var cookie=document.cookie;
console.log(cookie);//name=abc;age=18;

//解析字符串获取指定的数据内容
//3.设置cookie的有效期
document.cookie='id=66;expires="+new Date"2019-6-6 16:00'
//jquery.cookie.js插件
//第一种类型:会话cookie
// 1.设置值
    $.cookie("phone","19578454785");
    $.cookie('email','234@163.com');
 //2、获取值
    var phone=$.cookie('phone');
    console.log(phone);
    var email=$.cookie("email");
    console.log(email);


//第二种类型:设置长期cookie(具有指定有效期)
    $.cookie("address","广东深圳市",{
        expires:7 
       //expires不仅仅可以是日期类型的对象,也可以是以天为单位的数字
    });

     $.cookie("tel","0755-88888888",{
        expires:1/24
        //该cookie值就会保存一小时
    });

     $.cookie("birthday","1.1",{
        expires:new Date("2020-01-01 08:00")
        //对于这样的过期时间,已经在内部处理好了时区问题
    });

//删除指定的cookie
    $.removeCookie("birthday");

案例:

传递cookie页面的html,命名为a.html

<!-- 请输入用户名和密码:-->
<input id="userName" type="text"/>
<input id="passWord" type = "password"/>
<button id="btn">设置</button>
<button onclick="login()">传递cookie</button>
<button onclick="deletecookie()">删除</button>

a.html的js代码

//设置cookie
var setCookie =function(name,value,day){
     //当设置的时间等于0时,不设置expires属性,cookie在浏览器关闭后删除
    var expires =day *24 * 60 * 1000;
    var exp=new Date();
    exp.setTime(exp.getTime()+expires);
    document.cookie = name +"="+value+";expires="+exp.toUTCString();
};

//删除cookie
var delCookie=function(name){
     setCookie(name,"",-1);
};

//传递cookie
function login(){
      var name=document.getElementById('userName');
      var pass = document.getElmentById('passwords');
      setCookies('userName',name.value,7);
      setCookies('passWord',pass.value,7);  
      location.href='b.html' 
}

function deletecookie(){
   delCookie('userName',"",-1);
}


接受cookie的页面,此处定义为b.html

<button onClick='getcookie()'>获取</button>

b.html的js代码

/*获取cookies代码*/
var getCookies=function(name){
    var arr;
    var reg = new RegExp('(^| )'+name+'([^;]*)(;|$)');
    if(arr = document.cookie.match(reg)){
      return arr[2]
    }else{
      return null;
    }
};
/*点击获取按钮之后调用的函数*/
function getcookie(){
       console.log(getCookie('userName'));
       console.log(getCookie('passWord'));
}

 

方法三:使用h5的localStorage,或者sessionStorage存储对象类型

HTML5种的web storage包含两种存储方式:localStorage和sessionStorage,这两种方式存储的数据不会自动发给服务器,仅仅是本地保存,有大小限制。

localStorage是持久化的本地保存,只要你找不到其所在地没有主动删掉,就会一直存在。

sessionStorage是会话级别的本地保存,比如一个页面关闭的时候该页面设置的sessionStorage数据会自动消失,在不同浏览器窗口不会共享的,即使是同一个浏览器的同一个页面。当会话结束,sessionstroage保存值也会清空。

//使用方法
window.localStorage.setItem(key,value);//设置指定key的数据(JSON格式)存储 
window.localStorage.getItem(key);//对指定key进行取值
window.localStorage.valueOf()//获取全部值
window.localStorage.removeItem(key);//删除指定key的数据(单个) 
window.localStorage.clear();//清空所有的存储数据
window.localStorage.length//获得数据的数量 
window.localStorage.key(N)//获得第N个数据的key值
window.sessionStorage.setItem(key,value);
window.sessionStorage.getItem(key);
window.sessionStorage.removeItem(key); 
window.sessionStorage.clear();

//***  sessionStorage和localStorage用法相同
 
//注意: localStorage只能存储字符串的数据,对于数组或对象却不能直接存储
 
//解决方案:
//通过JSON对象提供的parse和stringify将其他数据类型转化成字符串,再存储到localStorage中就可以了
 
//比如:
       //将list数组存入 localStorage
       localStorage.setItem("list", JSON.stringify(list));  
       var list = localStorage.getItem("list");   //获取list
       var obj =JSON.parse(list);    //将json字符串解析成数组对象 obj
       console.log(obj);

案例如下:(对象存储的方式)

//存储对象的正确的方式.
//初始化对象
var obj={"name":"ellar","age":"12"};
var str= JSON.stringify(obj);//将对象”序列化“为 JSON 数据(字符串格式)
//语法如下:storage.setItem(keyName, keyValue); (名字,值)等价于("age",18);
//伪代码
localStorage.setItem(obj,str);//以字符串格式存储信息
var str2=localStorage.getItem(obj);//获取存储的信息,也是字符串格式
var obj2 = JSON.parse(str2);//将JSON数据反序列化为对象。
localStorage.setItem("lastname","lu");//或者
localStorage.lastname='lu';
localStorage.getItem("lastname");//或者
localStorage.lastname;

 案例

假如有A、B两个界面,要把A的值传给B。

 A页的代码

<!DOCTYPE html>
<html>
  <head>
	 <meta charset="UTF-8">
	<title>注册</title>
	<script type="text/javascript">
		function f1(){
		   var w = document.getElementById("n1").value;
		   var e = document.getElementById("s1").value;
		   localStorage.setItem("name",w);
		   localStorage.setItem("password",e);
		} 
	</script>
</head>
<body>
    <form>
         <p>name:</p>
	  <input id="n1" name="name" type="text" value=""/>
	  <p>password:</p>
	  <input id="s1" name="password" type="password" value=""><br>
	  <input name="button" type="button" value="Register" onclick="f1()" >
	  <a href="p.html">点击返回登录</a>
   </form>
 </body>
</html>

然后B页面中接收一下

	var yy = localStorage.getItem("name");
    	var xx = localStorage.getItem("password");
	console.log("用户名"+yy);
	console.log("密码"+xx);

其他参数获取介绍: 
//设置或获取对象指定的文件名或路径。
alert(window.location.pathname);


//设置或获取整个 URL 为字符串。
alert(window.location.href);


//设置或获取与 URL 关联的端口号码。
alert(window.location.port);


//设置或获取 URL 的协议部分。
alert(window.location.protocol);


//设置或获取 href 属性中在井号“#”后面的分段。
alert(window.location.hash);


//设置或获取 location 或 URL 的 hostname 和 port 号码。
alert(window.location.host);


//设置或获取 href 属性中跟在问号后面的部分。
alert(window.location.search);
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值