开发者

.append jquery, limit to one character per <span>

I have these two functions:

jQuery.fn.enterText = function(e){
if( $("#cursor").val() && e.keyCode != 32  ){
    var character = $("#cursor").val();
    $("#cursor").val("");
    this.append("<span class = 'text'>"+character+"</span>");
    $("#cursor").insertAfter(".text:last");
    $("#cursor").focus();

}
};

jQuery.fn.markCursor = function(e){
    $(this).focus();
   $(this).keyup(function(e) {
  $("#cursor-start").enterText(e);

});

};

What my problem is that if I text is entered rapidly, some elements will have more than one character, for example (abc). I wanted to know how to limit to one character in an efficien开发者_Go百科t manner, I thought of using an array, but would that not be too efficient?


This should do:

character = character.split("").join("</span><span class='text'>");
this.append("<span class='text'>" + character + "</span>");

I recommend changing some JQuery functions in ordinary JavaScript functions: document.getElementById("cursor-start") is universally supported, so use it instead of $("#cursor-start"). Optimized code:

jQuery.fn.enterText = function(e){
    var cursor = document.getElementById("cursor");
    var character = cursor.value;
    if(character && e.keyCode != 32){
        cursor.value = "";
        character = character.split("").join("</span><span class='text'>");
        this.append("<span class = 'text'>"+character+"</span>");
        $("#cursor").insertAfter(".text:last");
        cursor.focus();
    }

};

jQuery.fn.markCursor = function(e){
    $(this).focus();
    $(this).keyup(function(e) {
        $("#cursor-start").enterText(e);
    });
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜