$('button').on('click', function(){
let ht = $('#divstory').html();
console.log(ht);
});.divstory{
background:#eee;
min-height:54px;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="divstory" id="divstory" contenteditable="true"></div>
<br>
<button>CLICK</button>
在divstory中写入以下内容:
三百二十三号
525
七百二十七
979
然后点击button。
结果是:
323<div>525</div><div>727</div><div>979</div><div><br></div>
为什么323没有div标记?
以及如何获得像这样的新线条:
<div>323</div>
<div>525</div>
<div>727</div>
<div>979</div> 发布于 2018-12-21 16:36:41
如果您不关心保留换行符,可以将.html()替换为.text(),只返回没有html的文本。
如果希望保留换行符,但也不返回任何html,则需要使用字符div替换文本行中断来替换/n和br html元素。下面是一个同时适用于控制台或html输出的解决方案:
$('button').on('click', function(){
let ht = $('#divstory').html().replace(/<div>/g,"\n").replace(/<\/div>/g,"").replace(/<br>/g,"\n");
console.log(ht);
$("#result").text(ht);
});.divstory{
background:#eee;
min-height:54px;
}
#result{
white-space:pre;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="divstory" id="divstory" contenteditable="true"></div>
<br>
<button>CLICK</button>
<br>
<div id="result"></div>
发布于 2018-12-21 16:17:16
当您向内容可编辑的div提供输入时,它存储在单个textNode中,点击enter后,新文本被分配给divElement,但是第一个textNode是原样的,这意味着它不会改变。您可以使用以下示例手动更改它。
$('button').on('click', function(){
let ht = $('#divstory')[0].childNodes;
for(let child of ht){
if(child.constructor.name === 'Text'){
let newChild = document.createElement('div');
newChild.textContent = child.textContent;
$('#divstory')[0].replaceChild(newChild, child);
}
}
console.log($('#divstory').html());
});.divstory{
background:#eee;
min-height:54px;
white-space: pre;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="divstory" id="divstory" contenteditable="true"></div>
<br>
<button>CLICK</button>
发布于 2018-12-21 14:55:48
$('button').on('click', function(){
var html = $('#divstory').html();
var ht = remove_HtmlTags(html);
console.log(ht);
});
function remove_HtmlTags (html) {
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}.divstory{
background:#eee;
min-height:54px;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="divstory" id="divstory" contenteditable="true"></div>
<br>
<button>CLICK</button>
https://stackoverflow.com/questions/53886437
复制相似问题