JavaScript - 从文本中选择单词

标签 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。

最佳答案

您忘记将 .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>

关于JavaScript - 从文本中选择单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34697613/

相关文章:

javascript - 删除带有指令的特殊字符, Angular 不起作用

PHP 和多数据库选择

php - 如何获取字符串中某个单词前后的所有内容

linux - 删除包含指定单词的所有行

javascript - 在我的 asp.net 网站中调试 Javascript

javascript - 鼠标悬停图像在另一个位置弹出图像

linq - 使用 LINQ 呈现层次结构?

swift - Swift 中判断字符串中的字符是否为单词字符的最简单方法是什么?

javascript - 正则表达式数字与单个小数

MYSQL 选择日期最接近的记录