用js經過url傳參把數據從一個頁面傳到另外一個頁面

好長時間沒寫博客了,時值五一,外面處處人山人海,本寶寶仍是好好呆在家學習吧。好了,言歸正傳。在沒有後臺支持的狀況下,如何實現從一個頁面像另外一個頁面來傳遞數據呢?應該不少人遇到過這個問題吧。那我就來講說我在項目中遇到的時候是如何解決的。html

好比說,有兩個頁面,page1.html,和page2.html,在page1頁面向page2頁面傳遞數據能夠經過hash值。上代碼:數組

page1.html的代碼:學習

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>頁面1</title>
 6     <style>
 7      *{
 8          margin: 0;
 9          padding: 0;
10      }
11     </style>
12 </head>
13 <body>
14 <a href="index2.html#id1">跳轉到box1地方</a>
15 <a href="index2.html#id2">跳轉到box2地方</a>
16 
17 </body>
18 <script>
19     window.onload = function(){
20     }
21 </script>
22 </html>

page2.html代碼:url

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>頁面2</title>
 6     <style>
 7         #id1{
 8             width: 100px;
 9             height: 100px;
10             background: red;
11         }
12 
13         #id2{
14             width: 100px;
15             height: 100px;
16             background: pink;
17         }
18     </style>
19 </head>
20 <body>
21     <div id="id1">box1</div>
22     <div style="width: 10px;height: 10px;margin-bottom: 1000px;"></div>
23     <div id="id2">box2</div>
24 </body>
25 <script>
26     window.onload = function () {
27         console.log(window.location.href)//此處會打印出當前頁面的href值,爲http://localhost:63342/HTML_ExamplePractice/%E5%8D%9A%E5%AE%A2%E5%9B%AD%E6%8F%90%E5%89%8D%E7%BB%83%E4%B9%A0/index2.html#id1,井號後面的爲傳遞的參數,須要進行處理一下
28         //首先要獲取當前的href值
29         let url = window.location.href.split('#');
30         console.log(url);//打印出來是一個數組[‘http://localhost:63342/HTML_ExamplePractice/%E5%8D%9A%E5%AE%A2%E5%9B%AD%E6%8F%90%E5%89%8D%E7%BB%83%E4%B9%A0/index2.html’,'id1']  數組的第二個就是咱們傳遞的數據
31 
32 
33         function goHash(hash) {
34             if( hash == 'id1' ){
35                 console.log('打印出id1');//次處會打印出id1
36 
37             }else if ( hash == 'id2' ){
38                 console.log('打印出id2');//此處會打印出id2
39             }
40         }
41         goHash(url[1]);
42     }
43 </script>
44 </html>

當在page1頁面中點擊某一個a標籤的時候,會跳轉到page2頁面,而後經過獲取當前的href值,能夠得到咱們要傳遞的數據,後期通過處理以後加以利用。用到的知識點是hash值和錨點。。spa

相關文章
相關標籤/搜索