如何使用 JavaScript 设置 location 和 location.href?
众所周知,onclick 事件仅在用户点击元素时发生,它是一个纯 JavaScript 属性。每当您点击 onclick 事件时,它都会执行一些操作,例如显示消息或将用户重定向到另一个页面。onclick 事件在网站中应尽量少用,因为它可能会造成用户的困惑。因此,请明智地使用这些事件。
window.location 对象用于获取当前页面的 URL,并且它会将浏览器完全重定向到新页面。它可以不带前缀编写,即 window - 类似于 location.href、location 等。以下是 window location 的一些类型 -
location.href
location.hostname
location.protocol
location.assign()
location.pathname
在本文中,我们将学习如何使用 JavaScript 设置 location 和 location.href。
语法
以下是使用 JavaScript 在点击按钮后设置 location 和 location.href 的语法 -
location = URL or location.href = URL
参数
URL - 用于指定 URL
步骤
按照以下步骤在 JavaScript 中点击按钮后设置 location 和 location.href -
步骤 1 - 在 body 部分,我们定义了标题、按钮和脚本元素。
步骤 2 - 让我们为 HTML 文档的标题元素定义样式。
步骤 3 - 对于按钮元素,定义了 myLocation() 方法。使用此方法,当我们按下按钮时,位置将发生更改。
步骤 4 - 在 myLocation() 方法中,清楚地提到了应执行该方法功能的位置 URL。
步骤 5 - 点击按钮后,将触发 onClick 事件函数,并更改 URL 位置。
示例
在此示例中,我们将通过 JavaScript 在点击按钮后设置位置。
<html>
<body>
<h2>Setting the location using the Javascript</h2>
<p>Click the button to go to www.tutorialspoint.com</p>
<button onclick ="myLocation()">
Click Here to go to the URL
</button>
<script>
//function to setting the location using the Javascript
function myLocation() {
location = "https://tutorialspoint.com/";
}
</script>
</body>
</html>
示例
让我们再看一个使用 location.href 通过 JavaScript 设置位置的示例。
<html>
<body>
<h2>Setting the location using the Javascript<h2>
<button onclick ="hrefLocation()">
Click Here to go to the Tutorials Point
</button>
<script>
//function to setting the location using the Javascript
function hrefLocation() {
location.href = "https://www.tutorix.com/index.htm";
}
</script>
</body>
</html>
结论
在本文中,我们演示了如何设置 location 和 location.href 以及示例。我们在这里看到了两个不同的示例,我们使用了 location 属性来设置 URL 的位置。在第一个和第二个示例中,我们使用了“location 和 location.href”属性来设置指定的 URL。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP