我有一个pre
标签,用于显示从数据库中提取的文本(购物订单的注释)。我使用pre标签,因为它显示新行。
我contenteditable="true"
在上面使用它,以便用户可以编辑该字段,然后单击保存按钮进行保存。
但是,保存后,当我使用取字段的值时field.text()
,不会保留新行。
复制:
HTML:
<pre id="notes" contenteditable="true">Some
test
Txt
</pre>
JS:
// Works fine here
console.log($('#notes').text());
// add some text with new lines, then "blur" the text and you can see the issue happening in the log -- new lines not preserved
$('#notes').on('blur', function (e) {
console.log($('#notes').text());
});
我正在尝试但到目前为止还没有成功
// When user presses enter on an editable field.
$('#notes').on('keydown', function (e) {
if (e.keyCode === 13) {
// trap the return key being pressed and insert new line at THIS place --- how??? (Possibly not the most elegant solution either)
}
});
使用html()而不是text()可以在Enter上创建一个换行符。不过,使用html()会将<br>
标签包装到<div>
元素中,为防止这种行为,请使用document.execCommand()方法:
$('#notes').on('keydown', function (e) {
if (e.keyCode === 13) {
document.execCommand('insertHTML', false, '<br>');
return false;
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句