如何使用 JavaScript 或 jQuery 将一些文本插入文本区域?



我有两个文本区域 - 一个用于在其中粘贴一些文本,另一个用于双击后插入第一个文本区域中的单词。我怎样才能实现它?

我已经在以下情况下取得了一些结果: 1.将一些文本粘贴到文本区域 2.双击文本区域中的单词 3.看看这个词在里面有 ul 的div 中是如何出现的。这个词加为li。 请参阅案例代码:

//html block
<textarea name="" id="text" cols="30" rows="10" ondblclick="copyPaste()" >Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur minus iure suscipit quam expedita? Sed minus laboriosam natus quaerat autem enim accusantium, architecto officiis aliquam pariatur. Adipisci provident tenetur velit!</textarea>
<div id="wordList" class="wordListclass">
<ul id="myList">
<li></li>
</ul>
</div>
</body>
//js block for copy-pasting words after doubleclick on the text from the texarea with id ='text'
"use strict";
function copyPaste(){
var selection = window.getSelection();
console.log(selection.toString());
var node = document.createElement("LI");               
var selectionWithButton =  selection;
var textnode = document.createTextNode(selectionWithButton);      
node.appendChild(textnode);                             
document.getElementById("myList").appendChild(node);   
}

现在我需要摆脱并添加第二个文本区域。我想看看双击第一个文本区域中的文本后的单词如何出现在第二个文本区域中。重要说明 - 它们应具有以下结构:

字1
字2
字3

没有html标签,因为在第二个文本区域看到这些单词的列表后,我想将它们插入到数据库中,所以html标签(如我提供的代码)将是不可取的。 不幸的是,用文本区域替换div 元素不起作用。 感谢大家的阅读和帮助!

如果我理解正确,您只想将所选单词粘贴到第二个文本区域而不是列表中。

为此,您可以简单地使用文本区域的属性value附加文本。

为了使文本出现在不同的行上,您可以使用插入新行的字符n。您可以在此处找到有关转义序列的更多信息。

您的函数可能如下所示:

function copyPaste(){
// trim() is used here to remove the whitespace at the end of the word when you dblClick on a word
const selection = window.getSelection().toString().trim();
const textarea2 = document.getElementById("pasteTextarea");
if(!textarea2.value) {
// Don't add a new line when the textarea is empty
	textarea2.value = selection;
}
		else {
	textarea2.value += `n${selection}`;    
}
}
<textarea name="" id="text" cols="30" rows="10" ondblclick="copyPaste()" >Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur minus iure suscipit quam expedita? Sed minus laboriosam natus quaerat autem enim accusantium, architecto officiis aliquam pariatur. Adipisci provident tenetur velit!</textarea>
<textarea name="" id="pasteTextarea" cols="30" rows="10"></textarea>

const myList = document.querySelector("div#wordList ul#myList") // Get the list
function copyPaste(){
let textAreaValue = document.querySelector("textarea#text").value //get the written text in textarea
myList.innerHTML += `<li> ${textAreaValue} </li>` //put the "textAreaValue" in the list
}

像这样的东西?

最新更新