为什么这个用户脚本只做第一个 if?

Why is this userscript only doing the first if?

我正在编写用户脚本,但它似乎只适用于第一次比较:

(function() {
'use strict';

var noError = document.getElementsByClassName("noMistakeButton");
var next = document.getElementsByClassName("nextButton");
var wait = document.getElementsByClassName("understoodButton");
var okko = document.getElementsByClassName("buttonKo");
var exitOkko = document.getElementsByClassName("exitButton");

while(1)
{
    if( noError !== null)
    {
        noError.click();
    }

    if( next !== null)
    {
        exit.click();
    }

    if( wait !== null)
    {
        wait.click();
    }
    sleep(2);
    if( okko !== null)
    {
        exit.click();
    }

    if( exitOkko !== null)
    {
        exitOkko.click();
    }

} })();

我的目标是 运行 这个脚本在 AFK 时自如。 如您所见,网页上有许多按钮,每个按钮都不能是 :visible 或 :hidden。我的目标只是点击它们。

Here is the target page (static URL).

有些按钮只有 class 而没有 ID。其他人都有。

控制台报告:

ERROR: Execution of script 'AutoVoltair' failed!   noError.click is not a function

不清楚您希望完成什么。如果您尝试逐步执行一系列控件,请使用 Choosing and activating the right controls on an AJAX-driven site.

中说明的方法

问题中显示的那种代码只会播放 "Whac-A-Mole" 接下来的任何按钮 "popped up"。 (并且前提是前面的按钮已被删除。)

无论如何,回答问题:"why this code is only doing the first if?"。

这是因为用户脚本(和 javascript)在第一个严重错误 (有少数例外) 时停止 运行。另外:

  • noError.click 不是函数,因为 noError is a collection of elements, not a button.
  • 所有 getElementsByClassName 调用只执行一次。如果它要不断循环,你需要在循环内部重新检查。
  • 没有sleep()
  • while (1) 是一个非常糟糕的主意,它会冻结您的浏览器,甚至会导致您的 PC 崩溃。使用 setInterval 轮询页面。

这是更正了这些错误的 "Whac-A-Mole" 代码:

setInterval ( () => {
        var noError     = document.getElementsByClassName ("noMistakeButton");
        var next        = document.getElementsByClassName ("nextButton");
        var wait        = document.getElementsByClassName ("understoodButton");
        var okko        = document.getElementsByClassName ("buttonKo");
        var exitOkko    = document.getElementsByClassName ("exitButton");

        if (noError.length) {
            noError[0].click ();
        }
        if (next.length) {
            next[0].click ();
        }
        if (wait.length) {
            wait[0].click ();
        }
        if (okko.length) {
            okko[0].click ();
        }
        if (exitOkko.length) {
            exitOkko[0].click ();
        }
    },
    222  //  Almost 5 times per second, plenty fast enough
);


如果您想对点击进行排序,请使用链式 waitForKeyElements() 调用,如 this answer 所示。