【问题标题】:How to run a selector on a dynamically generated page?如何在动态生成的页面上运行选择器?
【发布时间】:2016-02-01 20:15:57
【问题描述】:

我有一个在 GM_addStyle 中工作但在 jQuery 中不工作的选择器。我想使用 CSS3 中不可用的 jQuery :contains()

但是,当我查看源代码时,我的页面上似乎不存在该 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");

【问题讨论】:

标签: jquery ajax google-chrome tampermonkey


【解决方案1】:

有时您可以等待窗口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() 内部,上面。

【讨论】:

    【解决方案2】:

    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");
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-07
      • 2011-06-15
      • 2012-05-19
      • 2018-07-28
      • 2019-10-30
      • 2013-04-01
      • 1970-01-01
      • 2021-12-30
      相关资源
      最近更新 更多