[英]How can I insert some text into a textarea using JavaScript or jQuery?
我有两个textareas - 一个用于粘贴其中的一些文本,另一个用于在双击它们之后插入第一个textarea中的单词。 我怎样才能实现呢?
我已经在以下情况下取得了一些成果:1。将一些文本粘贴到textarea中2.双击textarea中的单词3.看看这个单词如何出现在一个带有ul里面的div中。 这个词加为李。 查看案例代码:
//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);
}
现在我需要摆脱并添加第二个textarea。 我想看看在第二个textarea中出现在第一个textarea的文本上双击之后的单词是如何出现的。 重要提示 - 它们应具有以下结构:
字1
WORD2
WORD3
没有html标签,因为在我看到第二个textarea中的这些单词的列表后,我想将它们插入到数据库中,所以html标签(如我提供的代码中)将是不合需要的。 不幸的是,用textarea替换div元素不起作用。 感谢大家的阅读和帮助!
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
}
像这样的东西?
如果我理解正确,您只想将选定的单词粘贴到第二个textarea而不是列表中。
为此,您可以使用textarea的属性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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.