jQuery 回车键单击事件

来源:互联网 发布:软件开发年度工作计划 编辑:程序博客网 时间:2024/06/07 01:35
$(document).ready(function(){$("按下回车的控件").keydown(function(e){var curKey = e.which;if(curKey == 13){$("#回车事件按钮控件").click();return false;}});}); 

 $("#loginform").keydown(function(e){ var e = e || event, keycode = e.which || e.keyCode; if (keycode==13) {  $(".log_btn").trigger("click"); }});


form表单回车<strong style="color:black;background-color:#ff66ff">提交</strong>问题

我们有时候希望<strong style="color:black;background-color:#99ff99">回车键</strong>敲在文本框(input element)里来<strong style="color:black;background-color:#ff66ff">提交</strong>表单(form),但有时候又不希望如此。比如搜索行为,希望输入完关键词之后直接按<strong style="color:black;background-color:#99ff99">回车键</strong>立即<strong style="color:black;background-color:#ff66ff">提交</strong>表单,
而有些复杂表单,可能要避免<strong style="color:black;background-color:#99ff99">回车键</strong>误操作在未完成表单填写的时候就触发了表单<strong style="color:black;background-color:#ff66ff">提交</strong>。

要控制这些行为,不需要借助JS,浏览器已经帮我们做了这些处理,这里总结几条规则:

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

6.我们在处理表单的页面可以检验他是否点击了按钮来控制下面的程序。if($_POST['submit']){ 如果点击了按钮 程序继续}

实际应用的时候,要让表单响应<strong style="color:black;background-color:#99ff99">回车键</strong>很容易,保证表单里有个type=”submit”的按钮就行。而当只有一个文本框又不希望响应<strong style="color:black;background-color:#99ff99">回车键</strong>怎么办 呢?我的方法有点别扭,就是再
写一个无意义的文本框,隐藏起来。根据第3条规则,我们在用button的时候,尽量显式声明type以使浏览器表现一致。


通过以上可知只要把type="submit"改成type="button"然后js<strong style="color:black;background-color:#ff66ff">提交</strong>, 在不要有一个type=”text”的input就行了。就不会发生回车跳转。
但实验发现,ie和火狐不一样,火狐的submit按钮有掩藏的(display:block)和显现的都不行,必须全改。

0 0