开发者

Binding multiple events for the same element, then filtering specific actions

I am trying to bind a blur and keyup event handler to a textbox; I only want the logic to execute on all blur events and in the event of the keyup, only upon the user hitting Enter/ return (code 13). This should be simple if I can tell which of the开发者_开发问答 events were captured, but I can't seem to find something that describes what I need to look for. Quick few points for a simple answer.


You can use the jQuery event object to get info about the event. event.type will tell you which event was triggered.

$('#textBox').bind('blur keyup', function(e){
   if( e.type === 'blur' || (e.type === 'keyup' && e.which === 13) ){
     // Code...
   }
});

You can also just check event.which which will be undefined when it's a blur event.

$('#textBox').bind('blur keyup', function(e){
   if( typeof e.which === 'undefined' || e.which === 13 ){
     // Code...
   }
});


Use event.type:

$('input:text').bind('keyup blur',
                     function(e){
                         alert(e.type);
                     });

JS Fiddle.

$('input:text').bind('keyup blur',
                     function(e){
                         var t = e.type;
                         if (t == 'blur'){
                             $(this).css('background-color','red');
                         }
                         else if (t== 'keyup') {
                             $(this).css('background-color','green');
                         }
                     });

JS Fiddle demo.

Reference:

  • event.type.


$('input').keyup(function(e){

    var code = (e.keyCode ? e.keyCode : e.which);

    if(code == 13) /* enter was pressed */
        your_function();

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜