Javascript 通过javascript从contenteditable div中获取文本内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3593626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get the text content from a contenteditable div through javascript
提问by Suraj Air
I want retrieve the text content from a contentEditable div through javascript. What are the options of doing this? I've tried innerHTML but it doesn't work.
我想通过 javascript 从 contentEditable div 中检索文本内容。这样做有哪些选择?我试过innerHTML,但它不起作用。
采纳答案by Moin Zaman
use jQuery and do
使用 jQuery 并做
var content = $('#my-contenteditable-div').html();
var content = $('#my-contenteditable-div').html();
also look up these links:
还可以查看这些链接:
http://west-wind.com/Weblog/posts/778165.aspx
http://west-wind.com/Weblog/posts/778165.aspx
回答by Mircea
Why not use textContent for this:
为什么不为此使用 textContent :
var contenteditable = document.querySelector('[contenteditable]'),
text = contenteditable.textContent;
回答by B T
Unfortunately, I've found that innerTextis the only way to preserve newlines in contenteditable dom nodes. What I'm doing (tested only in chrome at the moment) is this:
不幸的是,我发现这innerText是在可编辑的 dom 节点中保留换行符的唯一方法。我正在做的(目前仅在 chrome 中测试)是这样的:
var innerText = editableDiv.innerText // using innerText here because it preserves newlines
if(innerText[innerText.length-1] === '\n')
innerText = innerText.slice(0,-1) // get rid of weird extra newline
return innerText
回答by user2028956
lblMailContentis the id of editable field.
lblMailContent是可编辑字段的 id。
var details= document.getElementById("lblMailContent").innerHTML;
Put this code in clientClick. It worked well for me.
把这段代码放在clientClick. 它对我来说效果很好。
回答by holysmoke
I solved it this way, because i need html-input:
我是这样解决的,因为我需要 html-input:
message = $('<div>').html(
$('#area').html()
.replace(/<(div|p|br)[^<]*?>/g, '<br />')
.replace(/<([(i|a|b|u)^>]+)>(.*?)<\/>/gim,
function(v) { return '' + escape(v) + ''; })
).text();
Allows the tags A, B, I, U and replaces Divs and Ps with BRs
允许标签 A、B、I、U 并用 BR 替换 Divs 和 Ps
回答by Rakesh
回答by Mr_DJA
Use this:
用这个:
function textFromDiv(selector) {
const element = document.querySelector(selector);
const text = element.html().replace(/<div>/g,"\n").replace(/<\/div>/g,"").replace(/<br>/g,"\n");
return text;
}```

