点击超链接,将页面中某个数据传到另一个页面

<input type="text" name="name">
<input type="text" name="age">
<a href="javascript:location.href='test.html?name='+document.getElementsByTagName('input')[0].value+'&age='+document.getElementsByTagName('input')[1].value;">test</a>
<p id="p1">1234567890</p>
<a href="javascript:;" onclick="convey()">测试二</a>
<a class="btn2" href="text2.html">使用cookie保存数据,在别的页面获取cookie值</a>
<a href="text2.html" class="btn3">使用localStorage保存数据,在别的页面获取值</a>
<script> function convey(){ var p=document.getElementById('p1').innerHTML; location.href='text2.html?key='+p; } //cookie不能在本地浏览,只能在线看 $(function(){ $('.btn2').click(function(){ var p2=$('p').text(); $.cookie('data',p2,1);//第一个参数为自定义的key,第二个参数为value值,第三个参数为有效时间 }) }) //localStorsge保存数据,在html5的文件夹里可以查看例子 var p3=$('p').text(); $('.btn3').click(function(){ localStorage.setItem('data1',p3);//第二个参数必须是字符串形式,如果是json形式,就需要使用JSON.Stringify()转化成字符串形式 })

另一个页面获取数据text2.html

  function GetQueryString(name)
    {//window.location.search  查问号
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null)return  unescape(r[2]); return null;
    }

    // 调用方法
    alert(GetQueryString("key"));
    //cookie方式
    console.log($.cookie('data'));
//localStorage方式 console.log(localStorage.getItem(
'data1'));

注:使用cookie保存数据,读取数据时,使用了cookie的插件设置cookie,必须加上,可以在网站上下

<!--cookie插件-->
    <script src="jquery-1.8.3.min.js"></script>
    <script src="jquery.cookie.js"></script>

读取url携带的数据时,还有另外一种方法

function GetRequest() {
  
 var url = location.search; //获取url中"?"符后的字串,包括?
 var theRequest = new Object();
 if (url.indexOf("?") != -1) {
  var str = url.substr(1);
  strs = str.split("&");
  for(var i = 0; i < strs.length; i ++) {
   theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1]);
  }
 }
 return theRequest;
}
var Request = new Object();
Request = GetRequest();
var v1;
v1 = Request[''key''];

其他参数获取介绍:

//设置或获取对象指定的文件名或路径。

 
1
alert(window.location.pathname);

//设置或获取整个 URL 为字符串。

 
1
alert(window.location.href);

//设置或获取与 URL 关联的端口号码。

 
1
alert(window.location.port);

//设置或获取 URL 的协议部分。

 
1
alert(window.location.protocol);

//设置或获取 href 属性中在井号“#”后面的分段。

 
1
alert(window.location.hash);

//设置或获取 location 或 URL 的 hostname 和 port 号码。

 
1
alert(window.location.host);

//设置或获取 href 属性中跟在问号后面的部分。

 
1
alert(window.location.search);
原文地址:https://www.cnblogs.com/zhaixr/p/6848422.html