JavaScript中表单内按钮点击后无法跳转页面的问题
问题分析与解决方案
这个问题的核心原因是:form标签内的button元素默认类型是submit,当你点击它时,浏览器会优先触发表单的提交行为,而你的demo()函数里的页面跳转逻辑会被这个默认行为打断,导致跳转失败。
原问题代码
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <form> <button onclick="demo()" name="btn">click here</button> </form> <script type="text/javascript"> function demo() { location.href="http://www.google.com"; } </script> </body> </html>
解决方法
方法1:显式设置button的type为button
给button添加type="button"属性,这样它就不会触发表单提交,只会执行你绑定的onclick事件:
<form> <button type="button" onclick="demo()" name="btn">click here</button> </form>
方法2:在点击事件中阻止默认行为
修改demo()函数,阻止按钮的默认提交行为,确保跳转逻辑能正常执行:
<script type="text/javascript"> function demo(event) { // 阻止默认提交行为 event.preventDefault(); location.href="http://www.google.com"; } </script> <!-- 调用时传递event对象 --> <button onclick="demo(event)" name="btn">click here</button>
或者也可以通过return false来阻止默认行为:
<script type="text/javascript"> function demo() { location.href="http://www.google.com"; return false; } </script> <button onclick="return demo()" name="btn">click here</button>
方法3:阻止表单的默认提交行为
如果你的表单确实需要保留提交功能,但又要在点击这个按钮时执行跳转,可以给form添加onsubmit事件并阻止默认行为:
<form onsubmit="return false;"> <button onclick="demo()" name="btn">click here</button> </form>
以上几种方法都能解决你遇到的问题,根据你的实际场景选择最合适的即可。
内容的提问来源于stack exchange,提问作者Vasanthi GV
相关产品推荐
相关产品推荐

