weird problem with .val on input and .append in jquery
I have this code in jquery:
$(document).ready(function () {
$("#main-edit").click( function() {
var cursorExists = $("#cursor").length;
if (!cursorExists){
$("#cursor-start").append("<input type='text' id = 'cursor' />");
$("#cursor").markCursor();
}
if (cursorExists){
$("#cursor").markCursor();
}
});
jQuery.fn.enterText = function(){
if( $("#cursor").val() ){
var character = $("#cursor").val();
$("#cursor").val("");
return this.append("<span>"+character+"</span>");
}
};
jQuery.fn.markCursor = function(){
$(this).focus();
$(this).keydown(function() {
$("#cursor-start").enterText();
});
};
});
My problem is in the enterText function. On the keydown function, I get the value of the input, store it, clear the input, and append the stored value. But when I type something like "foo"....I get "fo".....when I type "food"....I get "foo". So its not getting the last ente开发者_如何转开发red value for some reason.
You are getting the value on keydown, which is before the letter is added to the value. Get the value instead on keyup.
When you type "food", the last keydown event is when the value is "foo" and you press "d".
If you use keyup, the last keyup will be when you release "d", and the value will be "food"
Use keyup() instead of keydown()
精彩评论