首页 > 代码库 > 键盘回车事件导致页面刷新的问题
键盘回车事件导致页面刷新的问题
一个表单下,如果只有一个文本框时,按下回车将会触发表单的提交事件。
既然是只有一个文本框才会出问题,那么可以加一个隐藏的文本框,如下:
[html] view plaincopy
- <input id="hiddenText" type="text" style="display:none" />
现在代码成了这样:
[html] view plaincopy
- <form name="keywordForm" method="post" action="">
- <p id="profile_nav">
- <label for="profile"> 关键字搜索: </label>
- <input style="width:80; height:20" type="text" name="keyword" onkeypress="searchKeywordKeyboard(event)" />
- <input id="hiddenText" type="text" style="display:none" onkeypress="searchKeywordKeyboard(event)" />
- <input type="button" value="搜索" onClick="searchKeyword()">
- </p>
- </form>
结论是,可以采取两种方法解决这种问题:1.去掉表单;2.如果非得用表单,只要不让表单里有且只有一个文本框就OK了。
如果以上的方法还不足以让你去解决问题,那么你可以用以下方法来阻止因为回车而引起的表单自动提交:
[html] view plaincopy
- <form name="keywordForm" method="post" action="" onsubmit="return false;">
- <p id="profile_nav">
- <label for="profile"> 关键字搜索: </label>
- <input style="width:80; height:20" type="text" name="keyword" onkeypress="searchKeywordKeyboard(event)" />
- <input id="hiddenText" type="text" style="display:none" onkeypress="searchKeywordKeyboard(event)" />
- <input type="button" value="搜索" onClick="searchKeyword()">
- </p>
- </form>
就是在表单 form 后面加上一个 onsubmit 事件,返回 false,来阻止 form 提交。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。