首页 > 解决方案 > 从 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;
}

这是删除最后一段并在其中添加注释后的控制台。

在此处输入图像描述

标签: javascriptdommutation

解决方案


实际上,您的代码应该可以工作。您看到的是 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)
  }
});

小提琴


推荐阅读