jQuery 选择器可以与 DOM 突变观察器一起使用吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12596231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:50:57  来源:igfitidea点击:

Can jQuery selectors be used with DOM mutation observers?

jqueryhtmljquery-selectorsgreasemonkeymutation-observers

提问by hippietrail

HTML5 includes a concept of "mutation observers"to monitor changes to the browser's DOM.

HTML5 包含一个“变异观察者”的概念来监控浏览器 DOM 的变化。

Your observer callback will be passed data which looks a lot like DOM tree snippets. I don't know if they are exactly this or how they work really.

您的观察者回调将传递看起来很像 DOM 树片段的数据。我不知道它们是否正是这样,或者它们是如何工作的。

But when you are writing code to interact with a 3rd party site over which you have no control, say with a Greasemonkey script or Google Chrome user script, you have to inspect the tree of elements passed in to find which information is relevant to you.

但是,当您编写代码与您无法控制的 3rd 方站点进行交互时,例如使用 Greasemonkey 脚本或 Google Chrome 用户脚本,您必须检查传入的元素树以找出与您相关的信息。

This is much simpler with selectors, just like working with any DOM, than walking the tree manually, especially for cross-browser code.

这对于选择器来说要简单得多,就像使用任何 DOM 一样,比手动遍历树要简单得多,尤其是对于跨浏览器代码。

Is there a way to use jQuery selectors with the data passed to HTML5 mutation observer callbacks?

有没有办法将 jQuery 选择器与传递给 HTML5 突变观察者回调的数据一起使用?

回答by Brock Adams

Yes, you can use jQuery selectors on data returned to mutation observer callbacks.

是的,您可以对返回到突变观察者回调的数据使用 jQuery 选择器。

See this jsFiddle.

看到这个jsFiddle。

Suppose you had HTML like so:

假设你有这样的 HTML:

<span class="myclass">
    <span class="myclass2">My <span class="boldly">vastly</span> improved</span>
    text.
</span>


And you set an observer, like so:


然后你设置了一个观察者,像这样:

var targetNodes         = $(".myclass");
var MutationObserver    = window.MutationObserver || window.WebKitMutationObserver;
var myObserver          = new MutationObserver (mutationHandler);
var obsConfig           = { childList: true, characterData: true, attributes: true, subtree: true };

//--- Add a target node to the observer. Can only add one node at a time.
targetNodes.each ( function () {
    myObserver.observe (this, obsConfig);
} );

function mutationHandler (mutationRecords) {
    console.info ("mutationHandler:");

    mutationRecords.forEach ( function (mutation) {
        console.log (mutation.type);

        if (typeof mutation.removedNodes == "object") {
            var jq = $(mutation.removedNodes);
            console.log (jq);
            console.log (jq.is("span.myclass2"));
            console.log (jq.find("span") );
        }
    } );
}

You'll note that we can jQuery on the mutation.removedNodes.

您会注意到我们可以在mutation.removedNodes.



If you then run $(".myclass").html ("[censored!]");from the consoleyou will get this from Chrome and Firefox:

如果您随后$(".myclass").html ("[censored!]");从控制台运行,您将从 Chrome 和 Firefox 获得此信息:

mutationHandler:
childList
jQuery(<TextNode textContent="\n ">, span.myclass2, <TextNode textContent="\n text.\n ">)
true
jQuery(span.boldly)

which shows that you can use normal jQuery selection methods on the returned node sets.

这表明您可以在返回的节点集上使用普通的 jQuery 选择方法。

回答by Vita Pluvia

I don't have any personal code snippets for this one, but I have three resources that may help:

我没有这个的任何个人代码片段,但我有三个可能有帮助的资源:

Example from link #3 'jquery-mutation-summary' library:

来自链接 #3 'jquery-mutation-summary' 库的示例:

// Use document to listen to all events on the page (you might want to be more specific)
var $observerSummaryRoot = $(document);

// Simplest callback, just logging to the console
function callback(summaries){
    console.log(summaries);
}

// Connect mutation-summary
$observerSummaryRoot.mutationSummary("connect", callback, [{ all: true }]);

// Do something to trigger mutationSummary
$("<a />", { href: "http://joelpurra.github.com/jquery-mutation-summary"}).text("Go to the jquery-mutation-summary website").appendTo("body");

// Disconnect when done listening
$observerSummaryRoot.mutationSummary("disconnect");

回答by jmort253

I was working on a very similar problem for a Stack Exchange script I'm working on, and I needed to be able to monitor the DOM for changes. The jQuery docs didn't have anything helpful, but I did discover that the DOMNodeInserted event works in Chrome:

我正在为我正在处理的 Stack Exchange 脚本解决一个非常相似的问题,我需要能够监视 DOM 的更改。jQuery 文档没有任何帮助,但我确实发现 DOMNodeInserted 事件在 Chrome 中有效:

document.addEventListener("DOMNodeInserted", function(event){
    var element = event.target;

    if (element.tagName == 'DIV') {
        if (element.id == 'seContainerInbox') {
            //alert($('#seContainerInbox').parent().get(0).tagName);
            trimStoredItems();
            $('#seTabInbox').click();
            //   var newCount = getNewCount();
            // if there are new inbox items, store them for later
            storeNewInboxItems();
            applyNewStyleToItems();
        }
    }
});

I'm not 100% sure if this works in Firefox as I haven't got that far yet in the development process. Hope this helps!

我不是 100% 确定这是否适用于 Firefox,因为我在开发过程中还没有那么远。希望这可以帮助!

回答by Bart Jedrocha

I know this is an old question but perhaps this can help others searching for alternative solutions. I recently learned about Mutation Observers and wanted to experiment with using them alongside jQuery. I came up with two possible approaches and turned them into plugins. The code is available here.

我知道这是一个老问题,但也许这可以帮助其他人寻找替代解决方案。我最近了解了 Mutation Observers 并想尝试将它们与 jQuery 一起使用。我想出了两种可能的方法并将它们变成了插件。该代码可在此处获得

The first approach (jquery.observeWithEvents.js) uses jQuery's trigger()function to trigger either an insertNodeor removeNodeevent which can be bound to via jQuery's on()function. The second approach (jquery.observeWithCallbacks.js) uses traditional callback parameters. Please take a look at the README for examples and usage.

第一种方法 ( jquery.observeWithEvents.js) 使用 jQuery 的trigger()函数来触发可以通过 jQuery 的函数绑定到的insertNodeorremoveNode事件on()。第二种方法 ( jquery.observeWithCallbacks.js) 使用传统的回调参数。请查看 README 以获取示例和用法。