使用jquery获取keyup位置

Pra*_*eep 5 html jquery

可能重复:
如何在textarea中获得插入位置?

如果我在html textarea控件中的任何地方键入*,我需要获取keyup事件的当前位置"Welcome* to jQuery".所以我有*在欢迎意味着在第8位.如果有人能帮助我,请告诉我.

VDP*_*VDP 5

这会奏效.(注意:引号为7,否则为8)

$("#tf").on('keyup', function(){
    console.log($(this).val().indexOf('*'));
});?
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/Vandeplas/hc6ZH/

更新:多个解决方案*

$("#tf").on('keyup', function(){
    var pos = [],
        lastOc = 0,
        p = $(this).val().indexOf('*',lastOc);

    while( p !== -1){
        pos.push(p);
        lastOc = p +1;
        p = $(this).val().indexOf('*',lastOc);
    }
    console.log(pos);
});?
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/Vandeplas/hc6ZH/1/

更新:仅提供您刚输入的*char的位置

(function ($, undefined) {
    $.fn.getCursorPosition = function() {
        var el = $(this).get(0);
        var pos = 0;
        if('selectionStart' in el) {
            pos = el.selectionStart;
        } else if('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }
})(jQuery);

$("#tf").on('keypress', function(e){
    var key = String.fromCharCode(e.which);
    if(key === '*') {
        var position = $(this).getCursorPosition();
        console.log(position);
    } else {
        return false;
    }
});?
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/Vandeplas/esDTj/1/