如何使这两个事件的代码简短 [英] how to make this code short for both events

查看:113
本文介绍了如何使这两个事件的代码简短的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码.我怎样才能使它简短,以便它可以通过单击并输入来使用,所以我不必重复它.

I have the following code. how can I make it short so it work with click and enter so I dont have to duplicate it.

$(document).ready(function(){

    $(document).keypress(function(e) {
     if(e.which == 13) {
       $('form#myform').submit();
     }
   });

   $('#mybutton').click(function() {
     $('form#myform').submit();
   });  

});​

推荐答案

这将是一个简短的例子,它利用了事件冒泡的优势:

this would be a shorter one, it takes advantage of the event bubbling:

$(document).ready(function(){
   $(this).on('keypress click', function(e) {
       if(e.which == 13 || e.target.id==='mybutton')
           $('form#myform').submit();
   });  
});​

它是这样工作的: http://jsfiddle.net/e6L3W/

这篇关于如何使这两个事件的代码简短的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆