問題描述
我有一個按鈕和以下 javascript 例程.
I have a button and the following javascript routine.
$("button").keydown( function(key) {
switch(key.keyCode) {
case 32: //space
return false;
}
} );
據我了解,return false;
會阻止按鍵被處理.所以 $("button").click();
不會被調用.對于其他鍵碼,這按預期工作.例如,如果我截取40
,即向下按鈕,則頁面不滾動.
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.
我在 Firefox 中注意到了這種行為.
I noticed this behavior in Firefox.
為什么 return false;
不會停止空間上的按鈕單擊事件?javascript 規范對此有何評論?
Why does the return false;
does not stop the button click event on space? What does the javascript spec say about this?
推薦答案
希望這能回答你的問題:
Hope this answers your question:
<input type="button" value="Press" onkeydown="doOtherStuff(); return false;">
return false;
如果在 HTML 中的事件處理程序屬性的末尾調用,則成功取消跨瀏覽器的事件.據我所知,這種行為在任何地方都沒有正式規定.
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.
如果您改為通過 DOM 元素上的事件處理程序屬性設置事件(例如 button.onkeydown = function(evt) {...}
)或使用 addEventListener
/attachEvent
(例如 button.addEventListener("keydown", function(evt) {...}, false)
)然后只返回 false
來自該函數的功能并非在每個瀏覽器中都有效,您需要從我的其他答案中執行 returnValue
和 preventDefault()
內容.preventDefault
在 DOM 2 規范 并由大多數主流現代瀏覽器實現.returnValue
是特定于 IE 的.
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.
這篇關于為什么在 keydown 回調中返回 false 不會停止按鈕單擊事件?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!