如何通过id触发一个元素? (“.click();”不起作用)

How to trigger an element by id? (".click();" doesn't work)

我想在 Google 翻译中触发此元素,以便它始终自动更正我键入的所有内容。 https://i.snag.gy/NRsWFB.jpg

元素的 ID 是 "spelling-correction"。 我试过这个:

document.getElementById('spelling-correction').click();

还有这个:

function clickLink(link) {
    var cancelled = false;

    if (document.createEvent) {
        var event = document.createEvent("MouseEvents");
        event.initMouseEvent("click", true, true, window,
            0, 0, 0, 0, 0,
            false, false, false, false,
            0, null);
        cancelled = !link.dispatchEvent(event);
    }
    else if (link.fireEvent) {
        cancelled = !link.fireEvent("onclick");
    }

    if (!cancelled) {
        window.location = link.href;
    }
}

setInterval(function copyText() {
var correction123 = document.getElementById("spelling-correction");
correction123.clickLink();
 }, 100);

但不幸的是它们不起作用。我想以某种方式触发这个 "spelling-correction",这样我写的任何内容都会自动更正。 提前致谢!

问题是您点击的是 div。单击时 Div 不执行任何操作(除非另有说明)。

因为你想要的似乎是点击 link 本身,你应该尝试这样的事情:

childAnchors = document.querySelectorAll("#spelling-correction > a");
childAnchors[0].click();