I have this code :
jQuery.fn.enterText = function(e){
var $cursor = $("#cursor");
if (e.keyCode == 39){
e.preventDefault();
$cursor.val("");
var nextChar = $cursor.next();
$cursor.after(nextChar);
}
};
Im trying to move the #cursor to the right but it seems开发者_C百科 the browser does not allow it....the left arrow key works :
if (e.keyCode == 37){
$cursor.val("");
var previousChar = $cursor.prev();
$cursor.after(previousChar);
}
You should be using before
instead of after:
http://jsfiddle.net/Gq5HZ/1/
if (e.keyCode == 39) {
$cursor.val("");
var nextChar = $cursor.next();
$cursor.before(nextChar);
}
You are trying to add the element which is after the cursor, after the cursor... it's already there.
The left arrow key works because you're using after(), so you're actually moving the previous character after the cursor element.
I would recommend using insertBefore() and insertAfter() to move the cursor element instead, so your intent is clearer:
if (e.keyCode == 39) {
e.preventDefault();
$cursor.val("");
var nextChar = $cursor.next();
$cursor.insertAfter(nextChar);
}
if (e.keyCode == 37) {
e.preventDefault();
$cursor.val("");
var previousChar = $cursor.prev();
$cursor.insertBefore(previousChar);
}
精彩评论