javascript - 使用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.
});
解决方案
在列表项上使用 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()
.
推荐阅读
- java - Javafx SceneBuilder Table getter Methode 给了我一个 NullPointerException
- rabbitmq - 来自 RabbitMQ 队列的 Mule ESB 多线程消费者
- javascript - 类中的jquery动画回调函数
- haskell - Testing with Hakyll's MonadMetadata
- javascript - 获取隐藏在div内的值输入
- vba - Microsoft Word VBA pos 更改?
- message-queue - 每个租户的消息队列
- sql-server - TSQL - 基于重量的多个位置的随机获胜者
- r - 如何计算多个因素和水平的平均值?
- excel - VBA - 如何在“For”语句中按标题引用列