使用enter键事件时限制模糊事件

时间:2015-05-18 06:26:52

标签: jquery

我将keyup事件和blur事件绑定到一个对象。 输入密钥正常工作。但是一旦焦点丢失,就会发生不必要的模糊事件。当我使用keyup事件时,如何限制模糊事件。

实际上我需要对keyup事件和模糊事件进行相同的操作。用户将通过输入或仅通过焦点设置某些内容。

这是我的例子。

$('.classname').on({
    keyup: function (e) {
        if (e.keyCode == 13) {
            //Some Code
        }
    },
    blur: function (e) {
       //Some code
    }
});

2 个答案:

答案 0 :(得分:0)

Demo

var enterKeyPressed = false;
$('.classname').on({
  keyup: function(e) {
    if (e.keyCode == 13) {
      //Some Code
      enterKeyPressed = true;
      console.log('Enter key');
    }
  },
  blur: function(e) {
    if (enterKeyPressed) {
      //Some code
      enterKeyPressed = false;
    }
    console.log('Blur');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input type="text" class="classname" />

答案 1 :(得分:0)

如果处理函数相同,则可以将它们组合在一起。这可以如下完成。并在这个常用函数中使用event.stopImmediatePropogation()(在评论中由@Gurupasad Rao引用):

$(".classname").bind('blur keyup', function(e){
// Stuff that your function does... 
if(enterKeyPressed){ 
   e.stopImmediatePropogation();
  }
});
相关问题