如何在动态生成的页面上运行选择器? [英] How to run a selector on a dynamically generated page?
问题描述
我有一个选择器,该选择器可在GM_addStyle
中工作,但不能在jQuery中工作.我想使用CSS3中没有的jQuery :contains()
.
I have a selector which works in GM_addStyle
but not in jQuery. I want to use jQuery :contains()
which is not available in CSS3.
但是,当我查看源代码时,该ID似乎不存在于我的页面上,而是动态生成的.
我如何告诉Tampermonkey在整个页面加载后运行JS?
But, it appears that the id does not exist on my page when I view source but it's dynamically generated.
How do I tell Tampermonkey to run JS after the whole page loads?
我尝试了不同的JS @run-at
设置,但是没有运气.
I have tried different JS @run-at
settings but no luck.
//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");
推荐答案
有时您可以等待窗口load
事件,但是通常,您必须使用支持AJAX的技术.参见有关AJAX请求的Fire Greasemonkey脚本.
Sometimes you can wait for the window load
event, but in general, you must use AJAX-aware techniques. See Fire Greasemonkey script on AJAX request.
因此,使用 waitForKeyElements(),完整的Tampermonkey脚本将类似于:
So, using waitForKeyElements(), a complete Tampermonkey script would be like:
// ==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");
是无效的jQuery ,在这种情况下可能不需要.
Note that .css("color","blue","important");
is not valid jQuery and is probably not needed in this case.
如果这是您要做需要!important
的稀有网站之一,请使用:
If this is one of the rare sites where you do need !important
, use:
jNode[0].style.setProperty ("color", "blue", "important");
上方styleNode()
内部.
这篇关于如何在动态生成的页面上运行选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!