在 JavaScript 中使用 Onclick 重定向页面
 
本教程将教你如何在用户单击 HTML 按钮时创建 JavaScript 重定向。
我们将使用 onclick 事件来监听按钮上的点击事件。如果用户单击按钮,我们将执行重定向。
使用 JavaScript 中的 onclick 事件重定向到另一个页面
- 
初始设置 我们旨在解释如何在网站上执行此操作;但是,你可以在本地开发服务器上进行尝试。也就是说,下载像 Apache 这样的服务器。 你可以通过 XAMPP 安装获得 Apache。安装 XAMPP 后,你应该将本教程中的所有代码放在 htdocs文件夹中;你将在 XAMPP 安装目录中找到htdocs文件夹。最好在 htdocs中创建一个名为jsredirect的文件夹。所以jsredirect文件夹将包含你的代码。
- 
创建 HTML 表格 我们在下面有两个 HTML 代码。第一个是带有两个表单输入和一个按钮的 HTML 表单。 该按钮有一个我们将在 JavaScript 代码中使用的唯一 ID。同时,第二个 HTML 包含一个文本,内容为 Redirected from a form。下一个代码是我们将重定向到的 HTML 表单。将其保存为 home.html并带有 HTML 文档所需的文档类型。<body> <h1>Redirected from a form</h1> </body>In the next code, we have the code for the HTML form. Save it as form.html.
```html
<main>
	<form>
		<div class="form-row">
			<label for="first-name">First name</label>
			<input id="first-name" type="text" name="first-name" required>
		</div>
		<div class="form-row">
			<label for="last-name">Last name</label>
			<input id="last-name" type="text" name="last-name" required>
		</div>
		<div class="form-row">
			<button id="submit-form" type="submit">Submit</button>
		</div>
	</form>
</main>
```
- 
创建 JavaScript 代码 如果用户单击我们表单中的按钮,下面的 JavaScript 代码将执行重定向。 首先,我们使用 document.getElementById方法通过其 id 获取按钮。之后,我们将事件侦听器附加到按钮。在重定向函数中,我们使用 location.href方法来描述重定向的位置。在这种情况下,我们将其设置为保存为home.html的第二个 HTML 代码。因此,重定向 URL 是 http://localhost/jsredirect/home.html,其中jsredirect是我们项目文件夹的名称。如果你在实时服务器上,请将 localhost 替换为你网站的名称。 
```javascript
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 代码块为表单设置样式。 
```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;
}
```Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.
LinkedIn