Pre标签中加上contenteditable=true属性,换行符不会在元素的text()内容中保留

4

我有一个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)
    }
});

https://jsfiddle.net/6496pke5/

3个回答

2

在按下回车键时创建换行符,请使用html()而不是text()。 使用html()会将<br>标签包装到<div>元素中,如果要避免这种行为,请使用document.execCommand()方法:

$('#notes').on('keydown', function (e) {

    if (e.keyCode === 13) {
        document.execCommand('insertHTML', false, '<br>');
        return false; 
    }

});

Here is fiddle https://jsfiddle.net/6496pke5/1/


0

不会的,因为你正在做的是

console.log($('#notes').text());

自从你按下Enter键以创建新行时,<br>会添加到标记中,但它不会出现在textContent属性中,.text()是其简写形式的element。尝试使用:
console.log($('#notes').html());

你会看到新的换行符<br>被添加。


0
我建议使用一个隐藏标签pre和事件'blur'的代码,如下所示。
$('#notes-text').text($('#notes').html().replace(/<br>/g, '\n'));
console.log($('#notes-text').text());

console.log($('#notes').text());

$('#notes').on('keydown', function(e) {
  if (e.keyCode === 13) {
    document.execCommand('insertHTML', false, '<br>');
    return false;
  }
});

$('#notes').on('blur', function() {
  $('#notes-text').text($('#notes').html().replace(/<br>/g, '\n'));
  console.log($('#notes-text').text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre id="notes" contenteditable="true">Some

test


Txt

</pre>
<pre id="notes-text" style="display: none;"></pre>


你是怎么找到这个老帖子的 :D - Dan P.
有些问题永远不会过时的;-) - VBService

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接