$('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
内写入以下内容:
323
525
727
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>
答案 0 :(得分:0)
$('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>
答案 1 :(得分:0)
这是因为contenteditable添加了:
<div><br/></div>
进入其内容
将代码更改为:
$('button').on('click', function(){
var ht = $('#divstory').html();
ht = ht.replace("<br>", '');
console.log(ht);
});
答案 2 :(得分:0)
当您将输入内容提供给可编辑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>
答案 3 :(得分:0)
如果您不关心保留换行符,可以将.html()
替换为.text()
,以仅返回不带html的文本。
如果您想保留换行符,但又不返回任何html,即您需要使用文本换行符(使用字符{{1)替换div
和br
html元素}}。这是一个适用于控制台或html输出的解决方案:
/n
$('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;
}