javascript - 从 contenteditable div 中获取已删除的节点(Froala 编辑器)
问题描述
我正在尝试使用 MutationObserver 从 contenteditable 元素(在本例中为 Froala 编辑器)中获取 removedNodes,但在这种情况下.comment
,我没有获取已删除元素的类,而是得到了奇怪的类,例如.fr-marker
. 所以我正在寻找的是每次.comment
从编辑器中删除带有类的元素以记录该元素.data-comment
属性。一旦我得到了removedNode,我就知道如何处理获取数据属性。
这是完整示例的小提琴:https ://jsfiddle.net/chille1987/urwoLqsf/16/
HTML
<div id="elem">
<p>Click and <b>edit</b>, please</p>
<p>Another paragraph goes here</p>
<p>Third paragraph with <span class="comment" data-comment="2345">comment inside</span></p>
</div>
<link href="https://cdn.jsdelivr.net/npm/froala-editor@3.2.6/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/froala-editor@3.2.6/js/froala_editor.pkgd.min.js"></script>
这是我的 JS 文件
var editor = new FroalaEditor('#elem', {
events: {
'initialized': function () {
let observer = new MutationObserver(mutationRecords => {
mutationRecords.forEach(mutation => {
mutation.removedNodes.forEach(node => {
console.log(node.classList.value)
})
}); // console.log(the changes)
});
// observe everything except attributes
observer.observe(document.querySelector('.fr-view'), {
childList: true, // observe direct children
subtree: true // and lower descendants to
});
}
}
});
在 CSS 中突出显示的注释类
.comment {
background: yellow;
}
这是删除最后一段并在其中添加注释后的控制台。
解决方案
实际上,您的代码应该可以工作。您看到的是 Froala 编辑器如何处理编辑内容。最终,您将获得正确的元素,您所需要做的就是过滤已删除的节点:
mutation.removedNodes.forEach(node => {
if(node.nodeName === 'SPAN' && node.className === "comment"){
console.log(node.textContent)
const attribute = node.attributes.getNamedItem("data-comment")
console.log(attribute.value)
}
});
推荐阅读
- python - 在python中模拟类的属性的属性
- python - 在Python中查找字符串中多次出现的单词
- json - 如何使用角度 11 将多个标题行添加到 ag 网格中
- r - 如何只删除连续的重复行?
- ios - 由于无法完成操作,应用程序崩溃。(KCLErrorDomain 错误 1。)
- oracle - 从 RobotFramework DatabaseLibrary 执行 PLSQL 脚本文件抛出错误
- javascript - 条纹元素基于什么?他们如何保护它?
- python - Pyinstaller,只打包部分使用的第三方包,其余在另一台PC上调用
- powershell - Get-Content 无法从变量中读取
- pandas - pandas:查找每个分组活动的总小时数