input 回车导致页面刷新解决方法
input 的回车事件
若 form
里面只有一个 input
。当 input
发生回车事件时,会触发 form
自动提交数据事件,并刷新整个页面或跳转到 action
指定的路径。对于一些情况来说,并不需要刷新整个页面,需要的是局部刷新效果。
第一种方法:取消 form
的默认提交事件
<html>
<body>
<form onsubmit="return false;">
<input type="text" />
</form>
</body>
</html>
第二种方法:通过取消 input
的回车事件来阻止 form
提交数据
<html>
<body>
<form>
<input type="text" id="keyword" />
</form>
<script>
$("#keyword").keydown(function (e) {
if (e.keyCode == 13) {
// some code...
return false; // 取消 input 的回车事件
}
});
</script>
</body>
</html>
第三种方法:添加一个隐形 input,当 form
有多个 input
时,单个 input
的回车事件不会触发 form
的自动提交数据。
<html>
<body>
<form>
<input type="text" style="display: none;" />
<input type="text" />
</form>
</body>
</html>