JavaScript - 从文本中选择单词

时间:2016-01-09 18:57:26

标签: javascript select word

我正在尝试从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。

2 个答案:

答案 0 :(得分:3)

您忘记将.toString应用于txt



function get_selection() {
 var txt = '';
 if (window.getSelection) {
     txt = window.getSelection().toString();
 } else if (document.selection) {
     txt = document.selection.createRange().text;
 }
 document.getElementById("out").innerHTML = txt;
}

document.getElementById("txt").onclick = get_selection;

<div id="txt">"My text is long and wise and it consumes a lot of interwebs."</div>
<div id="out"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您需要将toString添加到getSelection:

console.log(txt.toString());

Jsfiddle:https://jsfiddle.net/h8u1a6ha/