javascript - 从文本区域追加值

标签 javascript jquery append

我是 Jquery/javascript 的初学者。我试图获取 textarea 的值来 append 一个 div 。但是当我用 jquery 执行此操作时,它会 append (我想)但只显示变量名称。为什么会发生这种情况?

Codepen

$(document).ready(function() {
 $('#textbox').click(function(event) {
 	if(event.which=13) {
    if($('#enter').prop("checked")) {

      $('#textbox').val('');
      event.preventDefault();

    }		
 	}
  $('#send').click(function() {

    var userMessage = $('#textbox').val();
    $('#textbox').val('');
    $('#container').append("userMessage");

  });
 
 });
});
* {
  	padding:0;
  	margin:0;
  }
  body {
  	background:#eee;
  }
 #container {
 	width:600px;
 	height:500px;
    background:#fff;
    border:1px solid black;
    margin:0 auto;
 }
 #controls {
 	margin:0 auto;
 	width:600px;
}
 #textbox {
 	resize:none;
 	width:540px;
 	}
 #send {
 	width:50px;
 	height:30px;
 	margin-top: 0px;
  position:absolute;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
<div id="controls">
<textarea id="textbox" placeholder="Enter your message here!"></textarea>
<button id="send">Send</button><br>
<input type="checkbox" id="enter"><br>
<label for="enter">Send on enter</label>
</div>

最佳答案

$(document).ready(function() {
  $('#textbox').keydown(function(event) {
    if(event.which==13 && $('#enter').prop("checked")==true) {
      $('#container').append("<br/>"+$('#textbox').val());
      $('#textbox').val('');
      event.preventDefault();
     }
  });

  $('#send').click(function() {
     var userMessage = $('#textbox').val();
     $('#textbox').val('');
     $('#container').append("<br/>"+userMessage);
  });

});

关于javascript - 从文本区域追加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32103912/

相关文章:

javascript - 如何创建像gmail一样的文件上传?

javascript - 如何更改 highcharts 最小和最大选择行为?

javascript - 如何跟踪react-admin dataProvider中的错误

当前上下文中不存在 javascript 参数

JavaScript ES6 原型(prototype)函数

javascript - FontAwesome 元素太大?

javascript - 为什么我的 JQuery AJAX 功能无法正常工作?

python - 正确 append

c - 在 C 段错误中追加链表

VBA:将具有值的字段添加到记录集