简体   繁体   English

如何通过ID触发元素? (“ .click();”无效)

[英]How to trigger an element by id? (“.click();” doesn't work)

I want to trigger this element in Google Translate, so that it would always auto-correct everything I type. 我想在Google翻译中触发此元素,以便它始终会自动更正我输入的所有内容。 https://i.snag.gy/NRsWFB.jpg https://i.snag.gy/NRsWFB.jpg

The element's id is "spelling-correction". 元素的ID为“拼写校正”。 I tried this: 我尝试了这个:

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

And this: 和这个:

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);

But they don't work unfortunately. 但不幸的是,它们无法正常工作。 I would like to somehow trigger this "spelling-correction", so that whatever I write would be auto-corrected. 我想以某种方式触发此“拼写校正”,以便我编写的任何内容都将被自动校正。 Thank you in advance! 先感谢您!

The issue is you're clicking on a div . 问题是您正在单击div Divs do nothing when clicked (unless otherwise specified). 单击时,Divs不会执行任何操作(除非另有说明)。

Since what you want seems to be clicking on the link itself, you should try something like this instead: 由于您想要的似乎是单击链接本身,因此您应该尝试这样的操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM