JQuery解决跳转无效的问题(.location.href)

前言

问题描述

做H5实训大作业时遇到的问题,发现在按钮点击事件里使用window.location.href进行页面跳转时,始终无法进行页面跳转

正文

1.button标签点击跳转事件无效

以下是我的示例代码

<form action="">
	......
	<button id="loginBtn">登录</button>
	......
</form>
<script>
	$("#loginBtn").click(function(){
			window.location.href="./index.html";
	})
</script>
出错原因及解决方法

form表单中,使用·button标签时若没有设置type=“button”,则button点击时默认会触发form表单的提交事件,所以window.location.href="xxxx"就无法跳转,因此解决方法就是在button标签上添加 type="button"即可

2.a标签点击事件无效

后来还了解到使用<a></a>标签做点击事件时,window.location.href="xxx"无效

出错原因及解决方法

点击<a></a>标签时触发了href属性的加载,所以又跳转回原来的页面了,故而window.location.href失效;因此将a标签的href属性设置成javascript:void(0)即可,即<a href=“javascript:void(0)”></a>

后记

做个梦给你

发布了65 篇原创文章 · 获赞 101 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_40563761/article/details/101203137