先放前端代码
// An highlighted block
<body>
<textarea></textarea>
<button onclick="submit()">点击</button>
</body>
<script th:src="@{/js/tinymce/tinymce.min.js}" referrerpolicy="origin"></script>
<script>
tinymce.init({
selector: 'textarea',
branding: false,
language:'zh_CN',
height:600,
selector:'textarea',
plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern autosave bdmap indent2em autoresize lineheight axupimgs',
toolbar1: 'code undo redo| forecolor backcolor bold italic underline strikethrough hr|' +
'|alignleft aligncenter alignright alignjustify|table image media| insertdatetime preview fullscreen',
});
function submit() {
var word='[[${noteInfo.getText()}]]';
tinyMCE.activeEditor.setContent(word);
}
</script>
问题一:富文本回显出html代码。
如下图
我们alert一下 [[${noteInfo.getText()}]],看一下数据格式。输出结果如下图:
可以看到Thymeleaf取出的数据带有转义字符,我们通过正则表达式替换出相应的符号。代码如下:
var text='[[${noteInfo.getText()}]]';
var req=/</g;
var req2=/>/g;
var req3=/"/g;
text=text.replace(req,'<');
text=text.replace(req2,'>');
text=text.replace(req3,'"');
alert(text);
结果如下图:
放进富文本里
可以看到回显成功
当我们回显一篇比较长的文章时又发生了以下错误
问题二:长文章无法显示
长文章部分内容:
回显发生错误:
富文本无法显示,我们看一下控制台报错:
显示我第三十二行代码,也就是获取文章内容时出错,我推断可能是长文章中的特殊字符导致变量出错。我们使用encodeURI对变量进行编码。代码如下:
下面展示一些 内联代码片
。
var text=encodeURI('[[${noteInfo.getText()}]]');
重新编码后的变量依然报错。
我们使用thymeleaf输出一下看看变量的数据,代码如下:
// An highlighted block
<a>
[[${noteInfo.getText()}]]
</a>
结果如下图:
我们可以看到在网页显示可以保持html类型,于是我想到了解决方法。
解决方法:
使用js获取a标签的text内容,将a标签因隐藏,然后放进富文本框中。代码如下:
<body>
<a id="toola" hidden="hidden">
[[${noteInfo.getText()}]]
</a>
<textarea></textarea>
</body>
<script th:src="@{/js/tinymce/tinymce.min.js}" referrerpolicy="origin"></script>
<script>
tinymce.init({
selector: 'textarea',
branding: false,
language:'zh_CN',
height:600,
selector:'textarea',
plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern autosave bdmap indent2em autoresize lineheight axupimgs',
toolbar1: 'code undo redo| forecolor backcolor bold italic underline strikethrough hr|' +
'|alignleft aligncenter alignright alignjustify|table image media| insertdatetime preview fullscreen',
init_instance_callback : function(editor) {
var text=$('#toola').text();
tinyMCE.activeEditor.setContent(text);
}
});
</script>
运行结果:
终于回显成功!
兜兜转转好在终于解决了问题,但是这个方法比较麻烦,希望会有更简单的解决方法!