javascript - 笔记功能、换行符和无内容

标签 javascript jquery html css bootstrap-4

我正在构建在我的网络应用程序上做笔记的功能。我遇到了两个问题:

我不知道如何识别换行符。我可以使用换行符的核心文本,但是当用户单击 Edit 时它在文本上显示 <br>如果他保存它只会显示 <br>纯文本。

此外,如果用户删除所有文本并单击“保存”,它也不起作用,只会打印 <textarea> .

非常感谢任何帮助!

$('#edit').click(function() {
  $('#edit').hide();
  $('#note').each(function() {
    var content = $(this).html();
    $(this).html('<textarea style="width:inherit">' + content + '</textarea>');
  });
  $('#save').show();
});

$('#save').click(function() {
  $('#save').hide();
  $('textarea').each(function() {
    var content = $(this).val(); //.replace(/\n/g,"<br>");
    $(this).html(content);
    $(this).contents().unwrap();
  });
  $('#edit').show();
});
#note {
  word-wrap: break-word;
  max-width: 40rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-6">
  <h5 class="card-tittle">Note</h5>
  <hr>
  <div class="container index">
    <div class="row">
      <div class="jumbotron col-md-12" id="note">
        Test Text.
      </div>
      <div class="col-md-12">
        <button class="btn btn-primary" id="edit"><span class="glyphicon glyphicon-edit"></span>Edit</button>
        <button class="btn btn-primary" id="save"><span class="glyphicon glyphicon-save"></span>Save</button>
      </div>
    </div>
  </div>
</div>

最佳答案

我想你想做这样的事情......

$('#edit').click(function() {
  $('#edit').hide();
  $('#note').each(function() {
    var content = $(this).html().replace(/<br>/g,"\n");
    $(this).html('<textarea style="width:inherit">' + content + '</textarea>');
  });
  $('#save').show();
});

$('#save').click(function() {
  $('#save').hide();
  $('textarea').each(function() {
    var content = $(this).val().replace(/\n/g,"<br>"); //.replace(/\n/g,"<br>");
    $(this).html("");
    $(this).append(content);
    $(this).contents().unwrap();
  });
  $('#edit').show();
});

演示:https://www.codeply.com/go/hAL9pWWUFk

关于javascript - 笔记功能、换行符和无内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53556672/

相关文章:

javascript - HTML5 拖放 - 如何删除 IE 上的默认重影图像

javascript - 如何将json对象保存为文件服务器端?

php - AJAX 响应和 PHP 循环

javascript - 在浏览器调整大小时从所有图像中删除类

javascript - 如何使用 JavaScript 覆盖 <p> 标签中的文本

javascript - 无法让 javascript 程序运行

javascript - JS根据数字显示数组值

javascript - 确定何时以 HTML 加载图像?

javascript - 我的命令提示符 JS 代码有什么问题?

javascript - Jquery在div中找到每个动态生成的选择,并添加类来选择选项值是否为 ""