繁体   English   中英

在contenteditable中删除HTML元素时如何触发事件

[英]How to fire an event when HTML element gets deleted in contenteditable

我有一个内容可编辑的div,其中包含一些html元素。 例如,假设我有:

<div contenteditable="true" id="myTextArea">
   Some content, <div id="div1">content in div</div>, 
   and more <span id="span1">content</span></div>

当用户在myTextArea中编辑文本并删除某些html元素时(通过粘贴新内容或仅退格文本),我希望每个html元素触发一个事件并告诉我该事件已删除。 关于如何执行此操作的任何想法?

您可以使用MutationObserver实现此目的。 要跟踪从contenteditable元素中删除的任何种类的节点,请观察以下示例

<div id="myTextArea" contenteditable="true">
    <input value="input" />
    <span contenteditable="false">span</span>
</div>

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {

        //console.log($(mutation.removedNodes)); // <<-- includes text nodes as well

        $(mutation.removedNodes).each(function(value, index) {
            if(this.nodeType === 1) {
                console.log(this) // your removed html node
            }
        });
    });
});

var config = { attributes: true, childList: true, characterData: true };

observer.observe($('#myTextArea')[0], config);

JSFiddle链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM