请注意,parent
在您的代码片段中应该是parentNode
.
无论如何,一般来说,对于动态元素,您需要检查并等待目标元素。如果需要单击某些内容,您的脚本必须单击它。(在 Google 网站上尝试使用页面 JS 功能通常效果不佳。Google 页面总是为编写脚本提供额外的“乐趣”。;))
您需要自由地使用轮询来补偿 AJAX 延迟。(挂钩 AJAX 事件或使用突变事件都具有很高的痛苦与成功率。轮询效果很好。)
最后,因为它是谷歌,仅仅触发一次投票是不够的,因为那些搜索选项不断被覆盖。
这是一个适用于美国版 Google 搜索结果的示例脚本(需要 jQuery):
// ==UserScript==
// @name _Google Search options add
// @include http://www.google.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// ==/UserScript==
if (window.top != window.self) //-- Don't run on frames or iframes.
return;
/*-- This script:
1) Waits for the "More search tools" control.
2) Clicks that control.
3) Waits for the target element
4) Adds our element before that one.
*/
waitForKeyElements ("#tbpi", clickMoreSearchToolsLink);
function clickMoreSearchToolsLink (jNode) {
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
jNode[0].dispatchEvent (clickEvent);
waitForKeyElements ("#qdr_y", addOurExtraNodes);
}
function addOurExtraNodes (jNode) {
jNode.before ("<li>Look at me, Ma!</li>");
}
/*--- waitForKeyElements(): A handy, utility function that
does what it says.
*/
function waitForKeyElements (
selectorTxt, /* Required: The jQuery selector string that
specifies the desired element(s).
*/
actionFunction, /* Required: The code to run when elements are
found. It is passed a jNode to the matched
element.
*/
bWaitOnce, /* Optional: If false, will continue to scan for
new elements even after the first match is
found.
*/
iframeSelector /* Optional: If set, identifies the iframe to
search.
*/
) {
var targetNodes, btargetsFound;
if (typeof iframeSelector == "undefined")
targetNodes = $(selectorTxt);
else
targetNodes = $(iframeSelector).contents ()
.find (selectorTxt);
if (targetNodes && targetNodes.length > 0) {
/*--- Found target node(s). Go through each and act if they
are new.
*/
targetNodes.each ( function () {
var jThis = $(this);
var alreadyFound = jThis.data ('alreadyFound') || false;
if (!alreadyFound) {
//--- Call the payload function.
actionFunction (jThis);
jThis.data ('alreadyFound', true);
}
} );
btargetsFound = true;
}
else {
btargetsFound = false;
}
//--- Get the timer-control variable for this selector.
var controlObj = waitForKeyElements.controlObj || {};
var controlKey = selectorTxt.replace (/[^\w]/g, "_");
var timeControl = controlObj [controlKey];
//--- Now set or clear the timer as appropriate.
if (btargetsFound && bWaitOnce && timeControl) {
//--- The only condition where we need to clear the timer.
clearInterval (timeControl);
delete controlObj [controlKey]
}
else {
//--- Set a timer, if needed.
if ( ! timeControl) {
timeControl = setInterval ( function () {
waitForKeyElements ( selectorTxt,
actionFunction,
bWaitOnce,
iframeSelector
);
},
200
);
controlObj [controlKey] = timeControl;
}
}
waitForKeyElements.controlObj = controlObj;
}