首页 > 解决方案 > 如何使用 JavaScript 或 jQuery 将一些文本插入到 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);   
}

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

单词1
单词
2 单词3

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

标签: javascriptjqueryeventstextarea

解决方案


    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
    }

像这样的东西?


推荐阅读