Prevent both blur and keyup events to fire after pressing enter in a textbox

后端 未结 8 422
粉色の甜心
粉色の甜心 2021-01-11 10:13

After pressing enter I would like that only the keyup event be fired but blur is fired first. How to cancel blur when

8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-11 11:14

    It has been brought to my attention than rather then providing hints I should give more complete explanations and code examples, so here it is: there is always the cheap way of setting a external variable:

    var triggerBlur = true;
    $(".textbox")
        .live({
           blur : function () { 
            if (triggerBlur) {// if not preceded by keyup 'Enter' event
                alert("blur Event fired");
            }
            // reset variable to true to allow the blur event to be triggered subsequently when not preceded by keyup 'Enter' event
            triggerBlur = true;
          },
          keyup : function (event) { 
            if(event.which === 13){ // Detect Enter
                alert("KeyUp fired after pressing Enter");
                triggerBlur = false;
            }
          });
    

    Also it's preferable to use event.which rather than event.keyCode (see http://api.jquery.com/event.which/ to understand why), and it is recommended to use the identity operator '===' rather than the equality '==' in javascript, as the latter is broken (see Which equals operator (== vs ===) should be used in JavaScript comparisons?)

提交回复
热议问题