gpt4 book ai didi

JavaScript - 从文本中选择单词

转载 作者:行者123 更新时间:2023-11-30 09:54:30 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com