$('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>
最佳答案
如果您不关心保留换行符,可以将.html()
替换为.text()
以仅返回不带html的文本。
如果要保留换行符,但又不返回任何html,即您需要使用字符div
用文本换行符替换br
和/n
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>