1. 程式人生 > >點擊超鏈接,將頁面中某個數據傳到另一個頁面

點擊超鏈接,將頁面中某個數據傳到另一個頁面

get innerhtml ear click ber cap java != plain

<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);

點擊超鏈接,將頁面中某個數據傳到另一個頁面