【问题标题】:Append value from textarea从 textarea 追加值
【发布时间】:2015-08-19 19:20:09
【问题描述】:

我是 Jquery/javascript 的初学者。我试图将 textarea 的值附加到一个 div 中。但是当我使用 jquery 执行此操作时,它会附加(我想)但只显示变量名。为什么会这样?

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>

【问题讨论】:

    标签: javascript jquery append


    【解决方案1】:
    $(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);
      });
    
    });
    

    【讨论】:

    • 谢谢老兄。现在我的头痛消失了。
    【解决方案2】:

    关闭 - userMessage 周围没有引号,因此请使用:而不是 append("userMessage")

    $('#container').append(userMessage);
    

    http://codepen.io/anon/pen/NqZGrm

    【讨论】:

    • 谢谢,我也像你在 sublime 上做的那样,在 chrome 上检查它是这样发生的吗? > i.imgur.com/FKDIEL1.png
    • 打开我提供的codepen - 你还看到这个问题吗?您的图像中的 css 似乎已关闭。
    • 我只是在 sublime 上遇到了这个问题,但下面的代码解决了这个问题。
    猜你喜欢
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 2017-02-06
    • 2017-07-15
    • 2023-03-22
    相关资源
    最近更新 更多