zoukankan      html  css  js  c++  java
  • 用js通过url传参把数据从一个页面传到另一个页面

    好长时间没写博客了,时值五一,外面到处人山人海,本宝宝还是好好呆在家学习吧。好了,言归正传。在没有后台支持的情况下,如何实现从一个页面像另一个页面来传递数据呢?应该很多人遇到过这个问题吧。那我就来说说我在项目中遇到的时候是如何解决的。

    比如说,有两个页面,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代码:

     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=" 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值和锚点。。

  • 相关阅读:
    ASP.NET安全问题-- 创建安全的Web应用程序
    浅谈ASP.NET内部机制(八)
    ASP.NET 配置文件纵横谈(一)
    项目开发-让设计模式成为一种心智
    浅谈ASP.NET内部机制(七)
    ASP.NET 配置文件纵横谈(二)
    GridView的分页是否真的是鸡肋呢?
    SQL开发中容易忽视的一些小地方(四)
    SQL开发中容易忽视的一些小地方( 三)
    怎样才能充分利用SQL索引
  • 原文地址:https://www.cnblogs.com/jiajia123/p/6792833.html
Copyright © 2011-2022 走看看