jQuery: 如何在按回车键后将textarea中的文本追加到段落中?

jQuery: How Do I Append Text From textarea To paragraph After I Presses Enter?

我想将用户键入的文本从 textarea 移动到用户 presses enter 时我选择的段落中。问题是 enter 已经编入 textarea。它的功能是换行,但我想将该功能替换为:

当用户按下回车键时,它会将文本从文本区域移动到

这是我的 html 段落和文本区域代码:

<hr id="LineOne">
<p id="UserInput"></p>
<hr id="LineOne">
<textarea placeholder="Type Message Here:"></textarea>

这是我的jQuery(这是我认为问题发生的地方,所以要多加注意这里:

$(document).ready(function(){
    $('textarea').bind("enterKey",function(e){
        textarea.moveTo('#UserInput');
    });
});
    $('textarea').keyup(function(e){
        if(e.keyCode == 13){
        $(this).trigger("enterKey");
        }
});

我非常 noobie/newbie 和 jQuery 并且我在 Stack overflow 中发现了另一个问题并对其进行了编辑以满足我的需要但是它没有按照我想要的方式工作你可以吗告诉我为什么它不起作用以及如何修复它。

而且,我怎样才能做到这一点,在用户发出消息后,它会在他们发送的消息后放置一个 space,这样它就不会将他们发出的每条消息都附加在同一行上?

我想这样做,如果我从 textarea 中删除文本,段落(或 UserInput)仍会保存该文本。

您可能正在寻找这个

$(document).ready(function() {
  $('textarea').keyup(function(e) {
    // Regex for matching new lines which will be replaced with <br />
    // to make new line onto the paragraph.
    var newval = $(this).val().replace(/(?:\r\n|\r|\n)/g, '<br />');
    var para = $('#myparagraph');
    
    // Keycode 13 is the Enter key
    if (e.keyCode == 13) {
      // Append the all text inside the textarea into paragraph
      para.append(newval);
      $(this).val(''); // Clear the textbox
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr/><p id="myparagraph"></p><hr/>
<textarea></textarea>

您不需要 jquery 来执行此操作。简单地做:

var input = document.getElementById('input');
var output = document.getElementById('output');

input.addEventListener('keydown', function(event) { // when a key is pressed
  if (event.keyCode == 13 && input.value != '\n') { // if the key is the enter key
    output.innerHTML += '<br>' + input.value;
    input.value = '';
  }
});

input.addEventListener('keyup', function(event) { // when a key is released
  if (event.keyCode == 13) { // if the key is the enter key
    input.value = '';
  }
});
<hr id="LineOne">
<p id="output"></p>
<hr id="LineOne">
<textarea id="input" placeholder="Type Message Here:"></textarea>