简体   繁体   English

如何在返回HTML5页面时触发函数? (JavaScript的)

[英]How to Trigger a Function when Returning to an HTML5 Page ? (javascript)

I'm going back and forth between two html pages - in my example Page1 and Page 2. When I move back from page 2 to page 1, I want to trigger a rebuild-my-html type function - similar to the way that 'onload' is triggered. 在两个html页面之间来回走动 - 在我的示例Page1和Page 2. 当我从第2回到第1页时,我 触发一个rebuild-my-html类型函数 - 类似于' onload'被触发。 Onload, of course, is only triggered when the app has been restarted/reloaded. 当然,只有在重新启动/重新加载应用程序时才会触发Onload。

I'm not sure if I need to do something before I move to page 2 (an event triggered by the user), or if there is a basic function I can keep for Page 1. 我不确定在转到第2页(由用户触发的事件)之前是否需要做某事,或者我是否可以保留第1页的基本功能。

I'm sure this is basic, but I just cannot find it! 我确定这是基本的,但我找不到它! I have been searching the web for DOM events related to onload. 我一直在网上搜索与onload相关的DOM事件。

Basic App Structure 基本的App结构

  1. Start on Page 1. 从第1页开始。
  2. The onload function executes onload函数执行

     function initLoad() 

It is triggered by 它由触发

      document.addEventListener('readystatechange', function()  

(In real app I Use a javascript onload function to layout some html dynamically) (在真实应用程序中我使用javascript onload函数动态布局一些html)

(In real app, user makes a choices to indicate detail they want to see layed out on Page 2) (在真实应用中,用户做出选择以指示他们希望在第2页上看到的细节)

  1. User Event button click, moves app to Page 2 用户事件按钮单击,将应用程序移动到第2页
  2. On Page 2 an onload function runs 在第2页上运行onload函数

      function init() 

    (In real app, user also initIates some other events) (在真实应用中,用户还会启动其他一些事件)

  3. User event returns app to Page 1 - I'm using 用户事件将应用程序返回到第1页 - 我正在使用

      history.go(-1); 

    because that is the only way I know to do that 因为这是我知道的唯一方法

  4. Upon returning to Page 1, I WANT APP to Return to Run a rebuild refresh type function 返回第1页后,我想要APP返回运行重建刷新类型功能

  5. Throughout the use of the app, I WANT the APP to epeatedly go back and forth from Page 1 to Page 2, triggering a refresh functions on both web pages 在整个应用程序的使用过程中,我希望APP能够在第1页到第2页之间来回切换,在两个网页上触发刷新功能

    (in my real app user is testing themselves on memorization skills. They go back and forth between Page 1 and 2. Page 1 will display information in new ways each time to indicate things that the user has demonstrated knowledge on, in Page 2) (在我的真实应用程序用户正在测试自己的记忆技能。他们在第1页和第2页之间来回切换。每次都会以新的方式显示信息,以指示用户已经证明的知识,在第2页)

Example Code 示例代码

Page 1 Code STACKexamplePage1Refresh.html 第1页代码STACKexamplePage1Refresh.html

    <!DOCTYPE html>
    <html>

    <body onunload="OnUnload()">

    </script>

    <script src="STACKExampleRebuild.js"></script>

     <h1> Page 1 </h1>

    <p id = changeMe>Want html info like this to be changed upon return from Page 2 and execution of rebuildExamplePage1 function</p>


    <button onclick="callAnothePage()">Go to Page 2</button>




    <script>
     </script>


    <script>

    function initLoad() {
       alert("Page  1 is loaded");
       console.log ("Page 1 is loaded");

    }

    function OnUnload() { // this does not seem to happen
      alert("Page  1 is UNloaded");
    }


    document.addEventListener('readystatechange', function() {
        // http://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object
        if (document.readyState === "complete") {
          initLoad();
        }// end if
      }); // end function

     window.onload = function() { // this is just another way of testing initLoad - it runs too
           alert("*Page  1 is REloaded*");
       }

     function callAnothePage()
     {
        window.location = "STACKexamplePage2Refresh.html"; // 
     }

    </script>

    </body>
    </html>

Page 2 Code STACKexamplePage2Refresh.html 代码STACKexamplePage2Refresh.html

    <!DOCTYPE html>
    <html>
    <body onload="init()">


      <script src="STACKExampleRebuild.js"></script>




    <h1> Page 2 </h1>

    <button onclick="historyBack()">Return To Learn Page</button>


     <script>
    function init() {
       alert("init function executed , Page 2 is loaded");
       console.log ("init function executed , Page 2 is loaded");
    }



    function historyBack() {   
             history.go(-1);
             rebuildExamplePage1(); // this function is in STACKExampleRebuild.js


            //navigator.app.backHistory(); // tried this too .... 1.15.17
            }     



    </script>

    </body>
    </html>

Sample Code: Java Script STACKExampleRebuild.js 示例代码:Java Script STACKExampleRebuild.js

     function rebuildExamplePage1(){
        alert("rebuildExamplePage1 function execute .... function  that will allow for Page  1 rebuild executed");
        console.log ("rebuildExamplePage1 function execute .... function  that will allow for Page  1 rebuild executed");

       /*
        var changePage1Info = "This info changed while on page 2";
        document.getElementById("changeMe").innerHTML = changePage1Info;
      */


         }

When I run the rebuildExamplePage1 function, and try to run the commented out part - changing the html id 'changeMe' - which is back on Page 1 - 当我运行rebuildExamplePage1函数,并尝试运行注释掉的部分 - 更改html id'changeMe' - 这是第1页的 -

I get the typical error that "null is not an object " in reference to the changeMe object 我在引用changeMe对象时得到“null不是对象”的典型错误

I think that is because the javascript function can't access the html on page 1, while it's on page 2 . 我认为这是因为javascript函数无法访问第1页上的html,而它位于第2页。 Though I was hoping that putting the commands after the history command might work. 虽然我希望在历史命令之后放置命令可能会起作用。

What I really want is some kind of function that is triggered whenever a user returns to an html page - a refresh/reentry type function 我真正想要的是当用户返回到html页面时触发的某种功能 - 刷新/重新输入类型功能

I bet there is some special kind of function, that I have not been able to find, that will execute upon a return to html - like onload does when I first load the page. 我打赌有一些特殊的功能,我无法找到,它会在返回到html执行 - 就像我第一次加载页面时的onload一样。

A few things I've tried that don't work 我试过的一些东西不起作用

The function onUnload for page 1, definitely does not execute at any time - I don't think this makes sense for this example anyway 第1页的onUnload函数肯定不会在任何时候执行 - 我认为无论如何这对于这个例子都没有意义

I found various examples that use persistant data, to pass things to other pages, but they always seem to be pages that have not yet been loaded. 我发现了各种使用持久数据的示例,将内容传递给其他页面,但它们似乎总是尚未加载的页面。 I already use persistent data in my onload type functions - but they only happen the first time the page is loaded, not upon return 我已经在onload类型函数中使用持久数据 - 但它们只在第一次加载页面时发生,而不是在返回时发生

I need to be able to go back and forth from Page 1 to Page 2 我需要能够从第1页到第2页来回走动

I will have the same problem the second time I return to Page 2. In my real app I bring up different detail info on Page 2 each time 第二次回到第2页时,我会遇到同样的问题。在我的真实应用程序中,每次都会在第2页上显示不同的详细信息

Add IDs to the body tag of each html page, then have a conditional set up to see if the body has the page 2 ID on "load" (I know it's readystatechange, but I cant recreate that in jsfiddle). 将ID添加到每个html页面的body标签,然后进行条件设置以查看主体是否在“load”上有第2页ID(我知道它是readystatechange,但我不能在jsfiddle中重新创建)。

 var page2 = document.getElementById('page-2'); if (page2 !== null) { alert('page 2 has been loaded'); } else { alert('page 2 has not been loaded') } 
 <body id="page-2"> </body> 

Okay so after your explanation in the comments on the original question, I think the best solution for you is going to be a pretty simple use of either cookies or localstorage. 好的,所以在您对原始问题的评论中作出解释后,我认为最适合您的解决方案是使用cookies或localstorage非常简单。 Either one will work for this scenario, but basically the flow would be something like this: 任何一个都适用于这种情况,但基本上流程将是这样的:

Page 1 links when clicked would store (either in a cookie or localstorage, I would probably use localstorage if audience browser usage would allow me to do so) what question the user clicked on. 点击后的第1页链接将存储(在cookie或localstorage中,如果用户浏览器使用允许我这样做,我可能会使用localstorage)用户点击了什么问题。

Page 2 would read the store and present the appropriate data to the user. 第2页将读取商店并向用户显示适当的数据。

When the user clicks or enters an answer on Page 2 you can calculate if it is correct or not, save the result to the store, and send the user back to page 1. 当用户在第2页上单击或输入答案时,您可以计算它是否正确,将结果保存到商店,然后将用户发送回第1页。

Page 1, on load, would need to read the store to determine which items were answered and if they were correct or incorrect. 第1页,在加载时,需要读取商店以确定哪些项目已被回答以及它们是否正确或不正确。

This is a lot of code to write so I'm not going to actually write it all out, but this should be enough to get you started. 这是很多要编写的代码所以我不打算把它全部写出来,但这应该足以让你开始了。

I have my sample app working. 我有我的示例应用程序工作。 Page 1 now returns to it's onload functionality when returning from Page 2. A persistent storage item is also recognized, so I will be able to have a separate set of logic for changing html, when I go back to page 1 after working on page 2 . 当从第2页返回时,页面1现在返回到它的onload功能。一个持久存储项也被识别,所以当我在第2页上工作后返回第1页时,我将能够有一组单独的逻辑用于更改html。 。 What I suddenly noticed (and why did I not before?) was that the reason that Page 2 gets reloaded as desired - executing it's onload function- is because Page 1 goes to Page 2 using a direct url reference - which will execute onload functions. 我突然注意到了什么(为什么我以前没有注意到?)是因为需要重新加载 - 执行它的onload函数 - 是因为Page 1使用直接url引用转到第2页 - 它将执行onload函数。

 function callAnothePage()
    {
    window.location = "STACKexamplePage2Refresh.html";  
     }

whereas Page 2 was using 'history' - which meant that onload functionality did not get triggered 而第2页使用的是“历史记录” - 这意味着onload功能没有被触发

  function historyBack() {   
          history.go(-1);

         }     

So two totally different techniques were being used. 因此使用了两种完全不同的技术。 Certainly seems obvious now, but my attention was always drawn elsewhere. 现在看来显而易见,但我的注意力总是在别处引起。 I of course tested to make sure that persistent data would stick around when going back and forth, and it appears to. 我当然进行了测试,以确保持续数据在来回传播时会保持不变,而且看起来如此。 I was previously sending persistent data from page 1 to page 2, so I figured it would - but you never know until you test. 我之前发送过第1页到第2页的持久数据,所以我认为它会 - 但是在你测试之前你永远都不会知道。

Using the history could certainly be useful - there are definitely times I might want to do that. 使用历史肯定是有用的 - 我肯定有可能想要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM