简体   繁体   English

检测一个按钮,然后在 JavaScript 中按下它

[英]Detect a button and then press it in JavaScript

I want to make a function that would detect a button on a web page and then click it.我想制作一个 function 来检测 web 页面上的按钮,然后单击它。 But I want it to click a specific item.但我希望它点击一个特定的项目。

function imready()
{
    var btn = document.getElementsByClassName('text-xxxs mb-02');
    for (var i = 0; i < btn.length; i++)
    {
        if (btn[i].innerText.indexOf('AK-47') > -1)
        {
            console.log('runtime');
            chrome.runtime.sendMessage({ type: 'dontrun', update: 1 }, function (response) {
        });
        btn[i].click();
        pressok();
    }
 }

How do I make it so that the var "btn" should equal to document.getElementsbyClassName('x') and also a different className ('y')?如何使 var "btn" 应该等于 document.getElementsbyClassName('x') 以及不同的 className ('y')?

As far as i understand your question, you can use document.querySelector('.classX.classY') to select the needed button with both classes.据我了解您的问题,您可以使用document.querySelector('.classX.classY')到 select 两个类所需的按钮。 That works for the case if you only need one button on the page selected, from your code i assume exactly that.如果您只需要所选页面上的一个按钮,这适用于这种情况,从您的代码中我假设正是如此。

Quoting from https://stackoverflow.com/a/29366682/10450049引自https://stackoverflow.com/a/29366682/10450049

getElementsByClassName() returns anHTMLcollection object which is similar to an array but not really an array so you can't call array methods using the returned value. getElementsByClassName()返回一个HTMLcollection object ,它类似于数组,但不是真正的数组,因此您不能使用返回的值调用数组方法。 One hack is to use Array's prototype methods along with.call()/.apply() to pass the returned object as the context.一种技巧是使用 Array 的原型方法以及 .call()/.apply() 将返回的 object 作为上下文传递。

 var elems = document.getElementsByClassName("royal"); var collapsedElems = document.getElementsByClassName("collapsed"); var earray = Array.prototype.slice.call(elems, 0); var concatenated = earray.concat.apply(earray, collapsedElems); console.log(concatenated)

Demo Fiddle演示小提琴

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

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