1. cookie 传值, 缺点: cookie储存是需要服务器支持的,本地直接运行静态文件是实现不了的
<script> //添加 cookie
function cp_add_cookie(num){
setCookie("cp_keynum",num,2);
}
//查找
function cp_seek_cookie(){
var cp_keynum=getCookie("cp_keynum");
var find_result = document.getElementById("find_result2");
find_result.innerHTML = "cp_keynum == " + cp_keynum;
} //设置 cookie 值的函数,创建一个函数用于存储访问者的名字
function setCookie(cname,cvalue,exdays){
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
//获取 cookie 值的函数,创建一个函数用户返回指定 cookie 的值
function getCookie(cname){
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>
2. LocalStorage和SessionStorage传值, 优点:本地静态文件可支持
if(typeof(Storage)=="undefined")
{
document.getElementById("result").innerHTML="对不起,您的浏览器不支持 web 存储。";
}
//保存数据
function save(cp_value){
var num = new Object;
num.cp_keynum ="key_num";
num.cp_num_value = cp_value;
var str = JSON.stringify(num); // 将对象转换为字符串
localStorage.setItem(num.cp_keynum,str);
alert("添加成功");
}
//查找数据
function find(){
var cp_keynum = "key_num";
var str = localStorage.getItem(cp_keynum);
var find_result = document.getElementById("find_result");
var num = JSON.parse(str);
find_result.innerHTML = cp_keynum + "==" + num.cp_num_value;
}
3. Url传值. 优点: 速度快. cookie 和 LocalStorage和SessionStorage 都存在速度慢,反应不过来的问题, 我在a页面写进去,在b页面读出来.有时会读到空值.
function getUrlParam(name){
//正则表达式过滤
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); console.log("location.search==="+location.search);
//substr(1):从字符串第一个位置中提取一些字符
console.log("location.search.substr(1)==="+location.search.substr(1));
//match():在字符串内检索与正则表达式匹配的指定值,返回一个数组给r
console.log("window.location.search.substr(1).match(reg)==="+window.location.search.substr(1).match(reg));
var r = window.location.search.substr(1).match(reg);
//获取r数组中下标为2的值;(下标从0开始),用decodeURI()进行解码
console.log("decodeURI(r[2])==="+decodeURI(r[2]));
if (r != null) return decodeURI(r[2]); return null; }