javascript 中设置window.location.href跳转无效问题解决办法
javascript中设置window.location.href跳转无效问题解决办法
问题情况
JS中设置window.location.href跳转无效
代码如下:
<scripttype="text/javascript"> functioncheckUser() { if(2!=1){ window.location.href="login.jsp"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"; } } </script> <divclass="extra"> <aclass="uibluerightfloatedprimarybutton"onclick="checkUser()"href="bookConfirm?userId=${account.id}&roomNum=${room.roomNum}&stime=${stime}&etime=${etime}"rel="externalnofollow"rel="externalnofollow">确认预订</a> </div>
原因是a标签的href跳转会执行在window.location.href设置的跳转之前:
如果是表单form的话 也会先执行form提交。
提交之后就已经不在当前页面了。所以window.location.href无效。
解决方法一
在js函数中加上
window.event.returnValue=false
这个属性放到提交表单中的onclick事件中在这次点击事件不会提交表单,如果放到超链接中则在这次点击事件不执行超链接href属性。
改成如下代码后window.location.href成功跳转:
<scripttype="text/javascript"> functioncheckUser() { if(2!=1){ window.location.href="login.jsp"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"; window.event.returnValue=false; } } </script> <divclass="extra"> <aclass="uibluerightfloatedprimarybutton"onclick="checkUser()"href="bookConfirm?userId=${account.id}&roomNum=${room.roomNum}&stime=${stime}&etime=${etime}"rel="externalnofollow"rel="externalnofollow">确认预订</a> </div>
解决方法二
点击事件中 onclick="checkUser()" 变成onclick="returncheckUser();"
并且在checkUser中return false;这样的话a标签的href也不会执行。这样就能window.location.href顺利跳转。
代码如下:
<scripttype="text/javascript"> functioncheckUser() { if(<%=flag%>!=1){ window.location.href="login.jsp"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"; returnfalse; } } </script> <divclass="extra"> <aclass="uibluerightfloatedprimarybutton"onclick="returncheckUser();" href="bookConfirm?userId=${account.id}&roomNum=${room.roomNum}&stime=${stime}&etime=${etime }">确认预订</a> </div>
解决方法三
如果是form体提交的话还可以把summit改成button调用js提交,这样window.location.href也会在js提交summit之前执行成功跳转。
如下:
functioncheckUser() { if(<%=flag%>!=1){ window.location.href="login.jsp"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"; returnfalse; } document.getElementById("form").submit(); } <formaction="addRoom"method="post"name="from"id="form"> <tablealign="center"border="1"class="commTable"> <tr> <tdclass="right"><span style="font-weight:blod;">房号:</span></td> <td><inputtype="text"name="roomNum"size="25" id="roomNum"/></td> </tr> <tr> <tdcolspan="2"align="center"><buttonvalue="添加" onclick="checkUser()"/></td> </tr> </table> </form>
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!