我想通过javascript从contentEditable div检索文本内容。这样做有哪些选择?我尝试过innerHTML,但它不起作用。
为什么不使用 textContent 来实现此目的:
var contenteditable = document.querySelector('[contenteditable]'),
text = contenteditable.textContent;
不幸的是,我发现
innerText
是在 contenteditable 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
lblMailContent
是可编辑字段的id。
var details= document.getElementById("lblMailContent").innerHTML;
将此代码放入
clientClick
。这对我来说效果很好。
使用 jQuery 并执行
var content = $('#my-contenteditable-div').html();
另请查找这些链接:
我这样解决了,因为我需要html输入:
message = $('<div>').html(
$('#area').html()
.replace(/<(div|p|br)[^<]*?>/g, '<br />')
.replace(/<([(i|a|b|u)^>]+)>(.*?)<\/\1>/gim,
function(v) { return '' + escape(v) + ''; })
).text();
允许标签 A、B、I、U 并用 BR 替换 Div 和 Ps
使用这个:
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;
}```
普通 JS 解决方案
html:
<div
contenteditable="true"
onkeyup="myFunction(this, event)"
></div>
js:
function myFunction(self, event){
console.log(self.innerText)
console.log(event)
}
jsfiddle
(在 Safari 中验证)
这是我的看法...
input = document.getElementsByTagName("div")[0];
input.onkeyup = function(){
text = "";
for(i=0; i<input.childNodes.length; i++){
text += input.childNodes[i].textContent + "\n";
}
text = text.trim();
console.log(text);
}
你可以用这个
document.querySelector("div").innerText.trim()