前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >表单提交刷新页面问题

表单提交刷新页面问题

作者头像
wangxl
发布2018-03-07 16:02:03
1.8K0
发布2018-03-07 16:02:03
举报
文章被收录于专栏:PHP在线PHP在线

今天开发中遇到了一个问题,刚开始没有头绪,不知道怎样解决,后来静下来一想,搜索下吧,经过搜索相关资料,很好的解决。

<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 type="button" value="搜索" onClick="searchKeyword()"> </p> </form>

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

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

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

现在代码成了这样:

<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了。

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

<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 提交。

注:如需转载本文,请注明出处(原文链接),谢谢。更多精彩内容,请进入简明现代魔法首页

知识在于积累,相信坚持的力量

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2015-07-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 php 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档