Core jQuery event modification problem
I am attempting to overwrite a core jQuery event, in this case the keydo开发者_Go百科wn
event. My intention is to preventDefault()
functionality of Left(37)
, Up(38)
, Right(39)
and Down(40)
to maintain the consistency of hot keys in my web application.
I am using the solution provided here for the conditional charCode preventDefault problem.
For some reason, my function overwrite is simply not firing, and I cannot put my finger on the problem. I am afraid that over the past 30 minutes this issue has resulted in some hair loss. Anybody have the remedy?
/*
Modify Keydown Event to prevent default PageDown and PageUp functionality
*/
(function(){
var charCodes = new Array(37,38,39,40);
var original = jQuery.fn.keydown;
jQuery.fn.keydown = function(e){
var key=e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
alert('now why is my keydown mod not firing?');
if($.inArray(key,charCodes))
{
alert('is one of them, do not scroll page');
e.preventDefault();
return false;
}
original.apply( this, arguments );
}
})();
A problem with your solution is that keydown
does not accept an event as it argument, so you mental model of what is going on is incorrect. How the event gets created is probably complicated, so why not just write a plugin which uses keydown
and builds upon it, slotting your logic in before a given callback:
(function($){
var charCodes = new Array(37,38,39,40);
$.fn.limitedkeydown = function(callback) {
this.keydown(function(e) {
if ($.inArray(e.keyCode, charCodes))
e.preventDefault();
callback(e);
});
};
})(jQuery);
That way the original (untouched) version is still available to you, so can equally use both methods:
$('selector').keydown(function(e) {});
$('selector').limitedkeydown(function(e) {});
精彩评论