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

How can I insert some text into a textarea using JavaScript or jQuery?

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

我已经在以下案例中取得了一些成果: 1.Paste 文本区域中的一些文本 2.Double 点击文本区域中的单词 3.See 这个词是如何出现在 div 里面的 ul 中的。字加为里。 见案例代码:

//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);   
}

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

word1
词2
word3

没有 html 标签,因为在第二个文本区域中看到这些单词的列表后,我想将它们插入数据库,所以 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
    }

是这样的吗?

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

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

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

您的函数可能如下所示:

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>