问题描述:在表单的提交事件里面,使用location.href属性无法去跳转到指定页面的问题?
<form >
<button>提交</button>
</form>
<script>
document.querySelector('form').addEventListener('submit', function() {
location.href = 'http://www.baidu.com'
})
</script>
这样点击提交按钮发现页面并不能跳转到页面上去!这是什么原因呢?
而我们这样的代码(如下)就可以跳转到指定的页面上去
<button>普通按钮</button>
<script>
document.querySelector('button').addEventListener('click', function () {
location.href = 'http://www.baidu.com'
})
</script>
这样的代码相信大家应该是能知道可以跳转的
那接下来大家看这样的一个代码片段(如下)
<form >
<button>提交</button>
</form>
<script>
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault()
location.href = 'http://www.baidu.com'
})
</script>
这样的代码页面也是可以跳转去指定页面的。
其实对比第一和第三段代码不难发现,后者能够跳转的原因就是因为在事件处理函数里面阻止了表单的默认行为,这样原本指定的location.href就能够正常运行。
所以,在表单的提交事件如果想要通过location.href去跳转的话,需要阻止表单的默认行为!当然,如果想直接跳转的话其实也可以通过form表单的action属性去设置!