没有关联的两个页面传值

第一种方法:

在H5中,window对象里面有一个storage事件,我们可以进行监听或者指定其事件处理函数的方法,在其他页面修改了sessionstorage或者localstorage中的值时,就会触发注册了storage事件。

以下几个属性需要了解一下:

1、event.key 属性:属性值为在 session 或 localStorage 中被修改的数据键值——属性名。

2、event.oldValue 属性:属性值为在 sessionStorage 或 localStorage 中被修改的值——更改前的属性值。

3、event.newValue 属性:属性值为在 sessionStorage 或 localStorage 中被修改后的值——更改后的值。

4、event.url 属性:属性值为修改 sessionStorage 或 localStorage 中值的页面的URL地址——更改属性值对应页面的url。

主要:当同源页面的某个页面修改了localStorage,其余的同源页面只要注册了storage事件,就会触发。

localStorage的例子运行需要如下条件:

  • 同一浏览器打开了两个同源页面
  • 其中一个网页修改了localStorage
  • 另一网页注册了storage事件

我们通过两个例子来体验一下。

修改localStorage中数据的页面——b.html:

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        
    </head>
    <body>
         <input type="text" id="input" />
      <input type="button" id="btn" />
<script> window.onload = function () {
          document.getElementById("btn").onclick = function () {
            var value = document.getElementById("input").value;
            if (value != "" | value != undefined) {
              localStorage.text = value;
            }
          }
        } </script> </body> </html>

实时监听的页面——a.html:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 7     </head>
 8     <body>
 9         <div id="div">Hello word</div>
10         <script>
11             window.onload = function () {
12          window.addEventListener('storage', function (e) {
13            if (e.key == 'test') {
14              document.getElementById("div").innerHTML = localStorage.test
15               //Callback(); 调用需要执行的方法
16                    }
17                 }) 
18               }
19         </script>
20     </body>
21 </html>

 

 

第二种方法:window.opener方法

  window.opener 返回的是创建当前窗口的那个窗口的引用,比如点击了a.htm上的一个链接而打开了b.htm,然后我们打算在b.htm上输入一个值然后赋予a.htm上的一个id为“name”的textbox中

     输入文本并赋值给a页面 ——b.tml:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        
    </head>
    <body>
         <input type="text" id="input" />
      <input type="button" id="btn" />

        <script>
            window.onload = function () {
          document.getElementById("btn").onclick = function () {
            var value = document.getElementById("input").value;
            if (value != "" | value != undefined){
              window.opener.document.getElementById("div").innerHTML = value;
              //window.opener.document.getElementById("#xx").click(); 调用a页面的方法,
            }        
          }
        }
        </script>
    </body>
</html>

 

 实时监听的页面——a.html:

 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="div">Hello word</div>
  </body>
</html>

 

posted @ 2019-07-16 16:01  蚂蚁的背包  阅读(401)  评论(0)    收藏  举报