JavaScript-从文本中选择单词

JavaScript-从文本中选择单词,javascript,select,word,Javascript,Select,Word,我正在尝试从div中的文本中选择一个单词。我想单击一个文本,并将一个单词放在指向变量的鼠标指针下方,以便进一步处理 function get_selection() { var txt = ''; if (window.getSelection) { txt = window.getSelection(); } else if (document.getSelection) { txt = document.getSelection(); } else if (doc

我正在尝试从div中的文本中选择一个单词。我想单击一个文本,并将一个单词放在指向变量的鼠标指针下方,以便进一步处理

function get_selection() {
 var txt = '';
 if (window.getSelection) {
     txt = window.getSelection();
 } else if (document.getSelection) {
     txt = document.getSelection();
 } else if (document.selection) {
     txt = document.selection.createRange().text;
 }
 console.log(txt);
}

document.getElementById("txt").onclick = get_selection;
我在控制台中看到的是整个段落:

Selection { anchorNode: #text ""My text is long and wise and it consumes a lot of interwebs."", anchorOffset: 18, focusNode: #text ""My text is long and strong and it consumes a lot of interwebs."", focusOffset: 18, isCollapsed: true, rangeCount: 1, caretBidiLevel: 0 }
…与单击的单词相反

请告知。我不想使用jQuery。

您忘了应用。toString to txt:

函数get_选择{ var-txt=; 如果window.getSelection{ txt=window.getSelection.toString; }如果选择文档,则为else{ txt=document.selection.createRange.text; } document.getElementByIdout.innerHTML=txt; } document.getElementByIdtxt.onclick=get\u选择; 我的文章很长,很有智慧,它消耗了很多互联网。 您忘记将.toString应用于txt:

函数get_选择{ var-txt=; 如果window.getSelection{ txt=window.getSelection.toString; }如果选择文档,则为else{ txt=document.selection.createRange.text; } document.getElementByIdout.innerHTML=txt; } document.getElementByIdtxt.onclick=get\u选择; 我的文章很长,很有智慧,它消耗了很多互联网。
您需要将toString添加到getSelection:

console.log(txt.toString());

jsIDLE:

您需要将toString添加到getSelection中:

console.log(txt.toString());
Jsfiddle: