Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

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

I have a button and the following javascript routine.

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

as I understood it, the return false; would stop the keypress from being processed. So $("button").click(); would not be called. For other keyCodes, this works as expected. For example, if I intercept40, which is the down button, the page is not scrolling.

I noticed this behavior in Firefox.

Why does the return false; does not stop the button click event on space? What does the javascript spec say about this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...