我正试图从textarea获取当前的单词,现在点击我的光标

时间:2013-11-18 07:31:37

标签: jquery

在这里,我使用以下代码选择单词,例如单击“我需要获取”

$('#select').click(function (e) {

    textAreaValue = $("#para")[0],
    startValue = textAreaValue.selectionStart,
    endValue = textAreaValue.selectionEnd,
    oldText = textAreaValue.value;
    text = oldText.substring(startValue, endValue);
    alert(text);
}

//我使用此代码获取放置光标的当前单词

$('#textarea')。click(function(){

    textAreaValue = $("#para")[0];
        startValue = textAreaValue.selectionStart;
    endValue = textAreaValue.selectionEnd;
    oldText = textAreaValue.value;
    startPosition = startValue;
    textlength = (textAreaValue.value).length;
    while(startPosition >= 0 ){
     if(oldText.substring(startPosition-1, startPosition) == ' '){
         break;
     }
     startPosition--;
    }
    endPosition = endValue;
    while(true){
        var eval = oldText.substring(endPosition, endPosition+1);
         if(eval == ' ' || eval == '\n' || eval == '\r' || eval == '\t'|| endPosition == textlength){
             break;
         }
         endPosition++;
        }

    text =  oldText.substring(startPosition, endPosition);
    textAreaValue.selectionStart = startPosition;
    textAreaValue.selectionEnd = endPosition;
    alert(text);
    return false;

});

2 个答案:

答案 0 :(得分:3)

如果用户突出显示文字,您可以获取所选文字:

$('textarea').on('click', function() {
    var text = $(this).html();
    var start = $(this)[0].selectionStart;
    var end = $(this)[0].selectionEnd;
    var text = text.substr(start, end - start);
    alert(text);
});

jsfiddle

如果用户只需单击textarea,您就可以获得光标所在的单词:

var stopCharacters = [' ', '\n', '\r', '\t']
$('textarea').on('click', function() {
    var text = $(this).html();
    var start = $(this)[0].selectionStart;
    var end = $(this)[0].selectionEnd;
    while (start > 0) {
        if (stopCharacters.indexOf(text[start]) == -1) {
            --start;
        } else {
            break;
        }                        
    };
    ++start;
    while (end < text.length) {
        if (stopCharacters.indexOf(text[end]) == -1) {
            ++end;
        } else {
            break;
        }
    }
    var currentWord = text.substr(start, end - start);
    alert(currentWord);
});

jsfiddle

答案 1 :(得分:0)

jQuery textRange插件可以做到这一点以及更多。