Javascript contenteditable=true的预标记-新行不会保留在元素';s text()内容
我有一个Javascript contenteditable=true的预标记-新行不会保留在元素';s text()内容,javascript,jquery,html,Javascript,Jquery,Html,我有一个pre标签,显示从数据库中获取的文本(购物订单的注释)。我使用pre标记是因为它显示新行 我在其上使用contenteditable=“true”,以便用户可以编辑该字段,然后单击保存按钮保存该字段 但是,在保存时,当我使用field.text()获取字段值时,新行不会被保留 复制: HTML: 我正在努力,但到目前为止还没有成功 不会,因为你正在做 console.log($('#notes').text()); 因为当您按键创建新行时,会添加到标记中,而该标记不会出现在元素的文本内
pre
标签,显示从数据库中获取的文本(购物订单的注释)。我使用pre标记是因为它显示新行
我在其上使用contenteditable=“true”
,以便用户可以编辑该字段,然后单击保存按钮保存该字段
但是,在保存时,当我使用field.text()
获取字段值时,新行不会被保留
复制:
HTML:
我正在努力,但到目前为止还没有成功
不会,因为你正在做
console.log($('#notes').text());
因为当您按键创建新行时,
会添加到标记中,而该标记不会出现在元素的文本内容属性中,其中元素的.text()
是
试试看
console.log($('#notes').html());
您将看到添加的新行。使用html()而不是text(),以便在按Enter键时创建换行符。
使用html()会将
标记包装到
元素中,但要防止这种行为,请使用document.execCommand()方法:
$('#notes')。关于('keydown',函数(e){
如果(如keyCode===13){
document.execCommand('insertHTML',false,
');
返回false;
}
});
这是小提琴
// 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)
}
});
console.log($('#notes').text());
console.log($('#notes').html());
$('#notes').on('keydown', function (e) {
if (e.keyCode === 13) {
document.execCommand('insertHTML', false, '<br>');
return false;
}
});