导航

jquery 回车事件

Posted on 2015-10-31 21:35  yiyishuitian  阅读(328)  评论(0编辑  收藏  举报

 

应用场景是这样的:有一个搜索框,输入关键字执行搜索.

所以写下以下代码

$("#txt").keydown(function (event) {
if (event.keyCode == 13) {
$("#btn").trigger("click");
}
});

但是总是被刷新掉,但是找了半天没有找到刷新的原因.

最后还是度娘啊~~度娘啊~~~,终于找到原因

 

<form id="form1" runat="server">

<input id="txtName" type="text" class="form-control" placeholder="请输入关键字" aria-describedby="basic-addon2"/>

</form>

如果表单form中只包含一个input 控件的时候,回车会自动提交,引起页面刷新事件,导致 查找失败.

解决方法有两种,

一  是再加入一个 input 控件就可以了.只要不显示此控件就可以了.这样在输入文字之后,再按回车就不会自动提交刷新了.

 <form id="form1" runat="server"> 
                       <input id="txtName" type="text" class="form-control" placeholder="请输入终端名称" aria-describedby="basic-addon2">
                        <input style="display: none;" type="text" /> 
</form>

二 添加onkeydown事件

<form id="form1" runat="server">

<input id="txtName" type="text" class="form-control" placeholder="请输入关键字" aria-describedby="basic-addon2"  onkeydown='if(event.keyCode==13){gosubmit();}' />

</form>

 

 

总结:

如果表单里有一个type=”submit”的按钮,回车键生效。  
如果表单里只有一个type=”text”的input,不管按钮是什么type,回车键生效。  
如果按钮不是用input,而是用button,并且没有加type,IE下默认为type=button,FX默认为type=submit。  
其他表单元素如textarea、select不影响,radio checkbox不影响触发规则,但本身在FX下会响应回车键,在IE下不响应。  
type=”image”的input,效果等同于type=”submit”,不知道为什么会设计这样一种type,不推荐使用,应该用CSS添加背景图合适些。 

 

 

来自:http://www.cnblogs.com/luoyanli/archive/2012/07/09/2582650.html