如何 运行 动态生成页面上的选择器?

How to run a selector on a dynamically generated page?

我有一个选择器在 GM_addStyle 中有效,但在 jQuery 中无效。我想使用 jQuery :contains(),它在 CSS3.

中不可用

但是,当我查看源代码时,该 ID 似乎不存在于我的页面上,但它是动态生成的。
我如何在整个页面加载后告诉 Tampermonkey 到 运行 JS?

我尝试了不同的 JS @run-at 设置,但没有成功。

//works
GM_addStyle(" \
   #T301444200 > tbody > tr.SelPrimary > td:nth-child(1) > nobr > span{ color: red; } \
");

//does not work
$("#T301444200 > tbody > tr.SelPrimary > td:nth-child(1) > nobr > span").css("color","blue","important");

有时您可以等待 window load 事件,但通常,您必须使用 AJAX 感知技术。参见 Fire Greasemonkey script on AJAX request

因此,使用 waitForKeyElements(),完整的 Tampermonkey 脚本如下:

// ==UserScript==
// @name     _Use jQuery on AJAXed content
// @match    http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.

waitForKeyElements (
    "#T301444200 > tbody > tr.SelPrimary > td:nth-child(1) > nobr > span", styleNode
);

function styleNode (jNode) {
    jNode.css ("color", "blue");
}

请注意 .css("color","blue","important");not valid jQuery,在这种情况下可能不需要。

如果这是您 需要 !important 的少数站点之一,请使用:

jNode[0].style.setProperty ("color", "blue", "important");

里面 styleNode(),上面。

Waiting for the element:

function waitForElement(id, callback, timeout){
    if('undefined' == typeof timeout) timeout = 30;
    timeout = timeout * 1000;
    var time = 0;
    var poops = setInterval(function(){
        if(time >= timeout) clearInterval(poops);
        if(document.getElementById(id)){
            clearInterval(poops);
            callback();
        }
        time += 100;
    }, 100);
}

One way to include jQuery:

(function(callback) {
  var script = document.createElement("script");
  script.setAttribute("src", "//code.jquery.com/jquery-1.11.3.min.js");
  script.addEventListener('load', callback);
  document.body.appendChild(script);
})

// main codez go in here
(function(){
  window.alert($('a').length+" Links");
});