如何让jQuery继续检查可能在以后创建的元素?

时间:2014-09-04 03:31:27

标签: jquery ajax greasemonkey

我正在尝试制作一个Greasemonkey脚本来隐藏一个网站上真正令人讨厌的div,几秒钟之后弹出。这些都不起作用:

$("#flyin").hide();
$(document).ready(function(){
  $("#flyin").hide();
});

我认为这是因为#flyin div尚未创建。我怎么告诉jQuery继续寻找这个div,也许每隔n秒,所以我可以隐藏它?

当我试图隐藏非js时,常常出现在页面上的常规旧div,它可以正常工作。

2 个答案:

答案 0 :(得分:2)

a utility for that (waitForKeyElements)

您的整个脚本只是:

// ==UserScript==
// @name     _YOUR_SCRIPT_NAME
// @include  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 work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/
waitForKeyElements ("#flyin", hideFlyin);

function hideFlyin (jNode) {
    jNode.hide ();
}


或者,如果节点仅在每页加载时出现一次,并且页面未通过AJAX完全更改,请使用:

//-- Unload after one run.
waitForKeyElements ("#flyin", hideFlyin, true);

答案 1 :(得分:1)

尝试

(function () {
    var $el = $("#flyin").hide();
    //the element is not already created
    if (!$el.length) {
        //create an interval to keep checking for the presents of the element
        var timer = setInterval(function () {
            var $el = $("#flyin").hide();
            //if the element is already created, there is no need to keep running the timer so clear it
            if ($el.length) {
                clearInterval(timer);
            }
        }, 500);
    }
})();