首页 > 解决方案 > 如何单击 .class 随机 # 次

问题描述

我需要在 1 到 10 之间单击 .CLASS 随机次数,在按键上我猜我需要使用Math.floor(Math.random())函数但不知道如何将它与我已经拥有的函数集成,我对此很陌生。先感谢您。

(function(tags) {
    tags = ["INPUT", "SELECT", "TEXTAREA"];
    addEventListener("keydown", function(ev, ele) {
        if (ev.shiftKey || ev.ctrlKey || ev.altKey || tags.includes(ev.target.tagName)) return;
        switch (ev.key.toUpperCase()) {
            case "Z": // test
                if (ele = document.querySelector(".CLASS")) ele.click();
                break;
        }
    });
})();

标签: javascriptjquerygoogle-chrome

解决方案


例如

<button class="button_example">Random Button 1</button>
<button class="button_example">Random Button 2</button>
<button class="button_example">Random Button 3</button>
<button class="button_example">Random Button 4</button>
<button class="button_example">Random Button 5</button>
<button class="button_example">Random Button 6</button>
<button class="button_example">Random Button 7</button>
<button class="button_example">Random Button 8</button>
<button class="button_example">Random Button 9</button>
<button class="button_example">Random Button 10</button>

var buttons = document.querySelectorAll('.button_example');
var randomNumber = Math.floor(Math.random() * buttons.length);
buttons[randomNumber].click();

推荐阅读