My code is available below, and here: http://jsfiddle.net/fRpCy/
var input = [];
input.push($('input'));
$(input).live('keydown', function (event) {
console.log('You have pressed a key!');
});
I would expect this code to respond to keypresses in the console. For some reason, it doesn’t. What is the problem with this code? (Note: I know how to fix it, I just don’t know what is wrong with it!)
Your code is expecting the
$()function to take an array of jQuery objects as an argument. You essentially have this:Per this jQuery documentation, I don’t think it supports that. The jQuery function will take:
Important to note is that it will NOT take an array of jQuery objects. An element array is not the same thing as a jQuery object array, though you can obtain an element array from a jQuery object with the
makeArray()method if you really wanted to.There are several alternatives that would work:
The simplest is to not save any intermediary value:
This one gets an actual DOM element into the input array so the input array is a type of array that the jQuery function supports (though I can think of no reason to actually use this code):
Or, if there are multiple input values, just save the jQuery object for future use:
Or, if you want an element array, you can get that like this:
Or, if what you really have is an array of jQuery objects and you want to combine those together into a new single jQuery object, this is one way to do that:
Or, a bit simpler way to do it:
Or, now I’ve found the .add() method on a jQuery object:
Incidentally, I’m finding the the array of DOM elements doesn’t work with .live(‘keydown’). I don’t know why. It works with:
And, since you have an array of DOM elements that already exist, there is no reason to use
.live()anyway. You can just use.keydown().jsFiddle working here: http://jsfiddle.net/jfriend00/qen2m/.