我们在本文中需要执行的任务是当用户导航到 HTML 页面时执行脚本。
我们可以使用“onpageshow Event”来完成上述任务(当用户导航到 HTML 页面时执行脚本)。在我们开始示例之前,让我们先了解一下 HTML 中 onpageshow 事件的定义和用法。
HTML 中的 onpageshow 事件在用户导航到网页时发生。每次加载页面时都会发生此事件。
以下是HTML中onpageshow事件的语法 -
<element onpageshow = "myScript">
以下是我们在HTML中使用onpageshow事件的示例,当用户在HTML中导航到一个页面时。
在示例中,
当用户在HTML中导航到一个页面时,我们使用了onpageshow事件。
我们在函数内部编写了一个alert()方法。因此,每当用户尝试导航到一个页面时,onpageshow事件将被触发。
<!DOCTYPE html> <html> <head> <title>Execute a script when a user navigates to a page in HTML?</title> </head> <body onpageshow="navigate()"> <h2>Execute a script when a user navigates to a page in HTML?</h2> <p><b>Note:</b> The <strong>"onpageshow"</strong> event in HTML will not supported in Internet Explorer 10 and before versions.</p> <script> function navigate() { alert("Welcome to the page!"); } </script> </body> </html>
正如我们在输出中看到的;当用户尝试导航到某个页面时,窗口上将显示警报。
在下面的示例中,
当用户在HTML中导航到一个页面时,我们使用了onpageshow事件。
我们在函数内部编写了一个打印语句。因此,每当用户尝试导航到一个页面时,onpageshow事件将被触发。
<!DOCTYPE html> <html> <head> <title>Execute a script when a user navigates to a page in HTML?</title> </head> <body onpageshow="navigate()"> <h2>Execute a script when a user navigates to a page in HTML?</h2> <p><b>Note:</b> The <strong>"onpageshow"</strong> event in HTML will not supported in Internet Explorer 10 and before versions.</p> <h2 id="heading"> </h2> <script> function navigate() { document.getElementById("heading").innerHTML = "Welcome to the page!"; } </script> </body> </html>
正如我们在输出中看到的,当用户尝试导航到某个页面时,将执行打印语句。
在下面的示例中,
当用户在HTML中导航到一个页面时,我们使用了onpageshow事件。
我们在函数内部编写了一个打印语句。因此,每当用户尝试导航到一个页面时,onpageshow事件将被触发。
在下面的代码中;我们编写了“window.onpageshow”,这里的窗口接口代表一个包含DOM文档的窗口。
<!DOCTYPE html> <html> <head> <title>Execute a script when a user navigates to a page in HTML?</title> </head> <body> <h2>Execute a script when a user navigates to a page in HTML?</h2> <h3 id="para"></h3> <script> function Navigate() { document.getElementById("para").innerHTML = "Welcome to the page!"; } window.onpageshow = Navigate; </script> </body> </html>
正如我们在输出中看到的,当用户尝试导航到某个页面时,将执行打印语句。