【问题标题】:Textarea jquery cannot hold what I have typed inTextarea jquery 无法保存我输入的内容
【发布时间】:2013-06-18 14:12:02
【问题描述】:
<script type="text/javascript" >
$(document).ready(function()
{
$(".comment").click(function(){

var element = $(this);
var id = element.attr("post_id");

$("#"+id).html('<form action="test.php" method="post"><textarea name="body" id="body_'+id+'"></textarea></form>');  

$("#body_"+id).focus();

return false;   

});
});

<a href="#" post_id="17" class="comment">Open</a>
<div id="17"></div>

为什么我每次在textarea中输入内容并点击.comment链接后,textarea的值变成空白,我应该如何保持我输入的内容不被删除?

【问题讨论】:

    标签: jquery textarea


    【解决方案1】:

    你正在用这一行覆盖你在 div 中的任何 html...

    $("#"+id).html('<form action="test.php" method="post"><textarea name="body" id="body_'+id+'"></textarea></form>');
    

    试着改成这样:

    var textArea = $("#body_"+id);
    var textAreaValue = textArea.length > 0 ? textArea.val() : '';
    $("#"+id).html('<form action="test.php" method="post"><textarea name="body" id="body_'+id+'">'+textAreaValue+'</textarea></form>');
    

    【讨论】:

      【解决方案2】:

      您需要阻止链接的默认行为,否则页面会重新加载:

      $(".comment").click(function(e){
          e.preventDefault();
          ...
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-26
        • 1970-01-01
        相关资源
        最近更新 更多