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

hip*_*ail 38 jquery html5 greasemonkey jquery-selectors mutation-observers

HTML5包含一个"变异观察者"概念,用于监控浏览器DOM的变化.

你的观察者回调将传递看起来很像DOM树片段的数据.我不知道它们究竟是这个还是它们是如何工作的.

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

对于选择器来说,这比使用任何DOM更简单,而不是手动遍历树,尤其是跨浏览器代码.

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

Bro*_*ams 53

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

看到这个jsFiddle.

假设你有这样的HTML:

<span class="myclass">
    <span class="myclass2">My <span class="boldly">vastly</span> improved</span>
    text.
</span>
Run Code Online (Sandbox Code Playgroud)


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

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") );
        }
    } );
}
Run Code Online (Sandbox Code Playgroud)

你会注意到我们可以在jQuery上mutation.removedNodes.


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

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

这表明您可以在返回的节点集上使用常规的jQuery选择方法.


Vit*_*via 7

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

来自链接#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");
Run Code Online (Sandbox Code Playgroud)