在 HTML 中,当用户导航到页面时执行脚本?
本文中我们需要执行的任务是在用户导航到 HTML 页面时执行脚本。
我们可以通过使用"onpageshow 事件"来完成上述任务(在 HTML 中,当用户导航到页面时执行脚本)。在开始示例之前,让我们先了解一下 HTML 中 onpageshow 事件的定义和用法。
HTML onpageshow 事件
HTML 中的 onpageshow 事件在用户导航到网页时发生。此事件每次页面加载时都会发生。
语法
以下是 HTML 中 onpageshow 事件的语法 -
<element onpageshow = "myScript">
以下示例展示了当用户导航到 HTML 页面时,我们在 HTML 中使用 onpageshow 事件。
示例 1
在本例中,
当用户导航到 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>
正如我们在输出中看到的,当用户尝试导航到某个页面时,窗口上会显示一个警告。
示例 2
在下面的示例中,
当用户在 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>
正如我们在输出中看到的,当用户尝试导航到某个页面时,打印语句将被执行。
示例 3
在下面的示例中,
当用户在 HTML 中导航到某个页面时,我们在 HTML 中使用了 onpageshow 事件。
我们在函数内部编写了打印语句。因此,每当用户尝试导航到某个页面时,都会触发 onpageshow 事件。
在下面的代码中,我们编写了"window.onpageshow",这里的 window 接口表示一个包含 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>
正如我们在输出中看到的,当用户尝试导航到页面时,打印语句将被执行。
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

