簡體   English   中英

如何使用JavaScript或jQuery將一些文本插入textarea?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM