首页 > 解决方案 > 使用jQuery双击后附加textarea

问题描述

我正在尝试添加一个允许您通过双击来编辑文本的逻辑。我想点击回车<br/>在文本中添加标签,但是在关注之后隐藏<br>标签并在没有的行下显示文本行
。这是我的代码:

var oriVal;
$("#parentUL").on('dblclick', 'li', function () {
    oriVal = $(this).text();
    $(this).text("");
    $("<textarea wrap='off' rows='1'></textarea>").appendTo(this).val(oriVal).focus();
});
$("#parentUL").on('focusout', 'li > textarea', function () {
    var $this = $(this);
    $this.parent().text($this.val().replace(/\n/g, '<br/>') || oriVal);
    $this.remove(); // Don't just hide, remove the element.
});

http://jsfiddle.net/wabLp/428/

标签: javascriptjquery

解决方案


在列表项上使用 CSS white-space属性。

$(function() {
  var oriVal;
  $("#parentUL").on('dblclick', 'li', function() {
    oriVal = $(this).text();
    $(this).text("");
    $("<textarea wrap='off' rows='1'></textarea>").appendTo(this).val(oriVal).focus();
  });
  $("#parentUL").on('focusout', 'li > textarea', function() {
    var $this = $(this);
    // good idea to trim
    var newVal = $.trim($this.val());
    $this.parent().text(newVal || oriVal);
    $this.remove(); // Don't just hide, remove the element.
  });

});
/* you want to maintain the whitespace characters */
li {
  white-space: pre-wrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id='parentUL'>
  <li>dad</li>
  <li>ads</li>
</ul>

如果您选择采用这种<br />方法,那么您将不得不使用.html()而不是.text().


推荐阅读