键盘回车事件导致页面刷新的问题

本文介绍了解决Ajax查询功能中表单自动提交的问题,提供了多种解决方案,包括移除表单标签、增加隐藏文本框及使用onsubmit事件阻止默认提交。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我最近在做一个 Ajax 查询的功能,代码如下:

1 < form name = "keywordForm" method = "post" action = ""
2 < p id = "profile_nav"
3 < label for = "profile" > 关键字搜索: </ label
4 < input style = "width:80; height:20" type = "text" name = "keyword" onkeypress = "searchKeywordKeyboard(event)" /> 
5 < input type = "button" value = "搜索" onClick = "searchKeyword()"
6 </ p >
7

</ form >

 

在文本框中输入关键字按回车,页面自动刷新了,结果肯定是没有实现无刷新搜索了。想了想,可能是按回车后默认提交了表单,于是将form去掉,果然不刷了。但是还是会有很多地方需要用到form。


一个表单下,如果只有一个文本框时,按下回车将会触发表单的提交事件。


既然是只有一个文本框才会出问题,那么可以加一个隐藏的文本框,如下:

1 < input id = "hiddenText" type = "text" style = "display:none" />

现在代码成了这样:

1 < form name = "keywordForm" method = "post" action = ""
2 < p id = "profile_nav"
3 < label for = "profile" > 关键字搜索: </ label
4 < input style = "width:80; height:20" type = "text" name = "keyword" onkeypress = "searchKeywordKeyboard(event)" /> 
5 < input id = "hiddenText" type = "text" style = "display:none" onkeypress = "searchKeywordKeyboard(event)" />
6 < input type = "button" value = "搜索" onClick = "searchKeyword()"
7 </ p >
8 </ form >

 

结论是,可以采取两种方法解决这种问题:1.去掉表单;2.如果非得用表单,只要不让表单里有且只有一个文本框就OK了。

 

如果以上的方法还不足以让你去解决问题,那么你可以用以下方法来阻止因为回车而引起的表单自动提交:

1 < form name = "keywordForm" method = "post" action = "" onsubmit = "return false;"
2 < p id = "profile_nav"
3 < label for = "profile" > 关键字搜索: </ label
4 < input style = "width:80; height:20" type = "text" name = "keyword" onkeypress = "searchKeywordKeyboard(event)" /> 
5 < input id = "hiddenText" type = "text" style = "display:none" onkeypress = "searchKeywordKeyboard(event)" />
6 < input type = "button" value = "搜索" onClick = "searchKeyword()"
7 </ p >
8 </ form >

 

就是在表单 form 后面加上一个 onsubmit 事件,返回 false,来阻止 form 提交。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值