JS实现把⼀个页⾯层数据传递到另⼀个页⾯的两种⽅式由于之前⾯试,被问到过此问题,所以今天特意整理了⼀下。由于⾃⼰技术⽔平有限,若存在错误,欢迎提出批评。
注册页面js特效本博客整理了两种⽅式从⼀个页⾯层向另⼀个页⾯层传递参数。
⼀. 通过cookie⽅式
1. 传递cookie页⾯的html,此处命名为a.html
请输⼊⽤户名和密码:
<input id="userName" type="text" />
<input id="passwords" type="password" />
<button id="btn">设置</button>
<button onclick="login()">传递cookie</button>
<button onclick="deletecookie()">删除</button>
2.a.html的js代码
//设置cookie
var setCookie = function (name, value, day) {
//当设置的时间等于0时,不设置expires属性,cookie在浏览器关闭后删除
var expires = day * 24 * 60 * 60 * 1000;
var exp = new Date();
exp.Time() + expires);
var pass = ElementById("passwords");
setCookie('userName',name.value,7)
setCookie('password',pass.value,7);
location.href = 'b.html'
}
function deletecookie() {
delCookie('userName',' ',-1)
}
3. 接受cookie的页⾯,此处定义为b.html
<button onclick="getcookie()">获取</button>
4. b.html的js代码
//获取cookie代码
var getCookie = function (name) {
var arr;
var reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = kie.match(reg)){
return arr[2];
}
else
return null;
};
//点击获取按钮之后调⽤的函数
function getcookie() {
console.log(getCookie("userName"));
console.log(getCookie("password"))
}
⼆. 通过url传递参数的⽅式
该案例也是从a.html向b.html页⾯传递参数
1. a.html的代码
<input type="text" value="猜猜我是谁">
<button onclick="jump()">跳转</button>
2.点击跳转按钮可以将input标签的value值传递到b.html
function jump() {
var s = ElementsByTagName('input')[0];
location.href='7.获取参数.html?'+'txt=' + encodeURI(s.value);
}
3. b.html中的代码
<div id="box"></div>
var loc = location.href;
var n1 = loc.length;
var n2 = loc.indexOf('=');
var txt = decodeURI(loc.substr(n2+1,n1-n2));
var box = ElementById('box');
box.innerHTML = txt;
三.通过localStorage
通过localStorage传递参数类似cookie。但是要注意:要访问⼀个localStorage对象,页⾯必须来⾃同⼀个域名(⼦域名⽆效),使⽤同⼀种协议,在同⼀个端⼝上。
1. a.html中的js⽂件
//将localStorage传递到哪个页⾯
location.href = 'b.html'
//设置localStorage
window.localStorage.setItem('user','haha');
2.b.html中的⽂件
<button onclick="getcookie()">获取</button>
function getcookie() {
//获取传递过来的localStorage
console.log(Item('user'))
}
总结
以上所述是⼩编给⼤家介绍的JS实现把⼀个页⾯层数据传递到另⼀个页⾯的两种⽅式,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。在此也⾮常感谢⼤家对⽹站的⽀持!