Why does returning false in the keydown callback does not stop the button click event?

前端 未结 3 1559
离开以前
离开以前 2020-12-01 17:03

I have a button and the following javascript routine.

$(\"button\").keydown( function(key) {
  switch(key.keyCode) {
  case 32: //space
    return false;
  }         


        
相关标签:
3条回答
  • 2020-12-01 17:37

    First, if you're detecting a printable character such as space, you would be better off with the keypress event. Secondly, the way to prevent the default action is to call preventDefault() on the event in non-IE browsers and set the event's returnValue property to false in IE.

    var button = document.getElementById("button");
    button.onkeypress = function(evt) {
       evt = evt || window.event;
       var charCode = evt.keyCode || evt.which;
       if (charCode == 32) {
           if (evt.preventDefault) {
               evt.preventDefault();
           } else {
               evt.returnValue = false;
           }
       }
    };
    

    I'm not a jQuery expert and I assume it takes care of obtaining the event for you:

    $("button").keypress(function(evt) {
       var charCode = evt.keyCode || evt.which;
       if (charCode == 32) {
           if (evt.preventDefault) {
               evt.preventDefault();
           } else {
               evt.returnValue = false;
           }
       }
    });
    
    0 讨论(0)
  • 2020-12-01 17:38

    You can just use one attribute in form to stop submit on enter.<form method="post" onkeydown="return false;">

    as like: onkeydown="return false;" in form attribute

    <form method="post" onkeydown="return false;"></form> 
    
    0 讨论(0)
  • 2020-12-01 17:40

    Hope this answers your question:

    <input type="button" value="Press" onkeydown="doOtherStuff(); return false;">
    

    return false; successfully cancels an event across browsers if called at the end of an event handler attribute in the HTML. This behaviour is not formally specified anywhere as far as I know.

    If you instead set an event via an event handler property on the DOM element (e.g. button.onkeydown = function(evt) {...}) or using addEventListener/attachEvent (e.g. button.addEventListener("keydown", function(evt) {...}, false)) then just returning false from that function does not work in every browser and you need to do the returnValue and preventDefault() stuff from my other answer. preventDefault is specified in the DOM 2 spec and is implemented by most mainstream modern browsers. returnValue is IE-specific.

    0 讨论(0)
提交回复
热议问题