Jquery 我正在尝试从文本区域获取当前单词,此时我的光标被单击

Jquery 我正在尝试从文本区域获取当前单词,此时我的光标被单击,jquery,Jquery,在这里,我通过使用以下代码选择单词,比如单击我需要获取 $('#select').click(function (e) { textAreaValue = $("#para")[0], startValue = textAreaValue.selectionStart, endValue = textAreaValue.selectionEnd, oldText = textAreaValue.value; text = oldText.substrin

在这里,我通过使用以下代码选择单词,比如单击我需要获取

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

    textAreaValue = $("#para")[0],
    startValue = textAreaValue.selectionStart,
    endValue = textAreaValue.selectionEnd,
    oldText = textAreaValue.value;
    text = oldText.substring(startValue, endValue);
    alert(text);
}
//我使用此代码获取光标所在的当前单词

$('#textarea')。单击(函数(){


jQuery插件可以完成这一点,甚至更多。

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

$('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);
});

如果用户只需单击文本区域,您就可以得到光标所在的单词:

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);
});
var stopCharacters=['','\n','\r','\t']
$('textarea')。在('click',function()上{
var text=$(this.html();
var start=$(此)[0].selectionStart;
var end=$(this)[0];
while(开始>0){
if(stopCharacters.indexOf(text[start])=-1){
--开始;
}否则{
打破
}                        
};
++开始;
while(结束<文本长度){
if(stopCharacters.indexOf(text[end])=-1){
++结束;
}否则{
打破
}
}
var currentWord=text.substr(开始,结束-开始);
警报(currentWord);
});

谢谢克里斯特·安德森
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);
});