简体   繁体   English

如何在JavaScript中删除突变记录对象

[英]How to delete mutation record objects in javascript

I'm observing changes on a Div element, that is being filled with child div's with ajax calls. 我正在观察Div元素上的更改,该更改被带有ajax调用的子div填充。 My aim is to make some checks within the observed Record objects and filter some of them. 我的目的是在观察到的Record对象中进行一些检查并过滤其中的一些对象。 How can i delete/remove/filter these mutation records from the observed mutation list? 如何从观察到的突变列表中删除/删除/过滤这些突变记录? and make them filtered in the web page. 并在网页中对其进行过滤。

I tried to remove the mutation record from the mutations list but it didn't work. 我试图从突变列表中删除突变记录,但是没有用。 Thanks for your help. 谢谢你的帮助。

Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};

var observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        var addedNode = mutation.addedNodes[0];
        if(addedNode){
            var innText = addedNode.innerText;
            //console.log("number " + i + " | " + addedNode.innerText);
            if(innText){
                if(innText.toLowerCase().indexOf(someText) > -1){
                    mutations.remove(mutation);
                }
            }
        }
    });

});

var config = {
    attributes: true,
    childList: true,
    characterData: true,
    characterDataOldValue: true,
    subtree: true
};
observer.observe(text, config);

I assume that your mutation object is a complex one and not a plain data type, therefore your "indexOf" check in your .remove Method will not remove anything. 我假设您的变异对象是一个复杂的对象,而不是普通的数据类型,因此您在.remove方法中进行的“ indexOf”检查不会删除任何内容。

You should create an additional method, like "checkForElement" or something. 您应该创建其他方法,例如“ checkForElement”或其他方法。 In that method you can decide what is equality for your mutation objects. 在这种方法中,您可以决定什么是您的变异对象相等。

There are already solutions for that at Stack Overflow, eg indexOf method in an object array? 在堆栈溢出中已经有解决方案,例如对象数组中的indexOf方法?

You can't abort the mutations since when the callback is executed, the mutation already occured. 您无法中止突变,因为在执行回调时,已经发生了突变。

What you can do instead is "rollback" the mutation using the information provided in the MutationRecord , particularly the addedNodes which you seem to care for. 您可以做的是使用MutationRecord中提供的信息“回滚” 变异 ,特别是您似乎需要关注的addedNodes You could simple iterate these, and for each node remove it from it's parent: 您可以简单地迭代这些,然后为每个节点将其从其父节点中删除:

if(node.parentNode) {
  node.parentNode.removeChild(node);
}

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

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