HTML页面之间跳转传值
1.借助JQuery,通过URL拼接,从而传递数据。
jquery.params.js用于两个HTML网页之间的传值。a.html?name=waley&age=20;b.html页面则可以这样获取:$.query.get("name)。
例如;将a.html页面的数据传递到b.html页面:
a.html:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script src="js/jquery-2.2.3.min.js"></script>
<script src="js/jquery.params.js"></script>
<title>a页面</title>
<script>
$(function(){
name = $("#name").text();
age = $("#age").text();
$("#btn").on("click",function(){
jump1();
});
});
function jump1(){
url = "b.html?name="+name+"&age="+age;//此处拼接内容
window.location.href = url;
}
</script>
</head>
<body>
<div id="name">wey</div>
<div id="age">20</div>
<button id="btn">跳转</button>
</body>
</html>
b.html页面通过$.query.get("name)获取。
b.html:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script src="js/jquery-2.2.3.min.js"></script>
<script src="js/jquery.params.js"></script>
<title>b页面</title>
<script>
$(function(){
getData1();
});
function getData1(){
var name = $.query.get("name");
var age = $.query.get("age");
$("#name").text(name);
$("#age").text(age);
}
</script>
</head>
<body>
<div id="name"></div>
<div id="age"></div>
</body>
</html>
2.利用JavaScript Cookies来保存页面之间的信息:
在a.html页面中将数据存入到document.cookie;
a.html:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script src="js/jquery-2.2.3.min.js"></script>
<title>a页面</title>
<script>
$(function(){
name = $("#name").text();
age = $("#age").text();
$("#btn").on("click",function(){
jump2();
});
});
function jump2(){
document.cookie = "name="+name;
document.cookie = "age="+age;
window.location.href = "b.html";
}
</script>
</head>
<body>
<div id="name">wey</div>
<div id="age">20</div>
<button id="btn">跳转</button>
</body>
</html>
在b.html中获取cookie的值,并使用split(';')将值进行切割,获得多个数组,然后循环读取出里面的值;
b.html:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script src="js/jquery-2.2.3.min.js"></script>
<script src="js/jquery.params.js"></script>
<title>b页面</title>
<script>
$(function(){
getData2();
});
function getData2(){
var name=getCookie("name");
var ages = getCookie("age");
if (name!="")
{
$("#name").text(name);
}
if(ages!=""){
$("#age").text(ages);
}
}
//循环得到相应的值
function getCookie(cname)
{
var ss = document.cookie;
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0)
return c.substring(name.length,c.length);
}
return "";
}
</script>
</head>
<body>
<div id="name"></div>
<div id="age"></div>
</body>
</html>