سؤال

im having a slight issue, with trying to programmatically find out the keycode value of a char. this is what I have at the moment.

var delimiter = ',';

//some where down the page

control.keyup(function(e)
{
    var key = delimiter .charCodeAt(0);
    if(e.keycode == key)
    {
       //do something
    }
}  

So when I press the ',' on the keyboard key has a value of 44 whilst e.keycode is 188. How to find out the keycode value of the variable delimiter ?

هل كانت مفيدة؟

المحلول

The keyup event returns a keycode not an ASCII code. If you switch to the keypress event you can retreive the ASCII code. This should match the value received by charCodeAt which returns the unicode value of a character, which happens to align with the ASCII code for the first 128 characters. See this reference.

var delimiter = ',';
var key = delimiter.charCodeAt(0);
document.getElementById("test").onkeypress = function(e){
    if((e.keyCode || e.which) == key){
       alert("Cat's out of the bag! OHHH YEAH!");
    }
};
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top