在 JavaScript 中使用 Onclick 重定向页面
本教程将教你如何在用户单击 HTML 按钮时创建 JavaScript 重定向。
我们将使用 onclick 事件来监听按钮上的点击事件。如果用户单击按钮,我们将执行重定向。
使用 JavaScript 中的 onclick
事件重定向到另一个页面
-
创建 JavaScript 代码
如果用户单击我们表单中的按钮,下面的 JavaScript 代码将执行重定向。
首先,我们使用
document.getElementById
方法通过其 id 获取按钮。之后,我们将事件侦听器附加到按钮。在重定向函数中,我们使用
location.href
方法来描述重定向的位置。在这种情况下,我们将其设置为保存为home.html
的第二个 HTML 代码。因此,重定向 URL 是
http://localhost/jsredirect/home.html
,其中jsredirect
是我们项目文件夹的名称。如果你在实时服务器上,请将 localhost 替换为你网站的名称。
let button = document.getElementById('submit-form'); button.onclick = function(e) { e.preventDefault(); // Replace localhost and the folder name // based on your setup location.href = 'http://localhost/jsredirect/home.html'; }
-
测试我们的代码
现在我们已经设置了 HTML 文件和 JavaScript,我们可以测试它是否有效。启动你的本地服务器并通过
localhost/<your_project_folder>
导航到你的项目文件夹。加载后,如果你愿意,可以使用任意数据填写表单。此外,你可以实现确保用户填写表单的逻辑。
但是,重要的是要确保在单击按钮时重定向有效。所以,继续点击按钮。
如果你做的一切正确,你的网络浏览器应该会重定向到第二个 HTML 文件。我们在下面的 GIF 图像中展示了一个重定向示例。
-
CSS 代码
下一个 CSS 代码块为表单设置样式。
* { padding: 0; margin: 0; box-sizing: border-box; } main { margin: 2em auto; width: 50%; outline: 1px solid #1a1a1a; } .form-row { padding: 0.5em; display: flex; justify-content: space-around; } .form-row input { width: 45%; padding: 0.2em; } .form-row button { padding: 0.5em; }
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。