如何使用JavaScript设置位置和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.href。
语法
使用JavaScript在点击按钮后设置位置和location.href的语法如下所示:
location = URL
or
location.href = URL
参数
- URL - 用于指定URL
步骤
按照以下步骤在JavaScript中设置位置和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://www.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.href,并附上了示例。我们在这里看到了两个不同的示例,我们使用了位置属性来设置URL的位置。在第一个和第二个示例中,我们使用了“位置和location.href”属性来设置指定的URL。
极客笔记