简体   繁体   English

自动单击 javascript 中的按钮

[英]automatically clicking a button in javascript

I have this button:我有这个按钮:

<button class="btn btn-primary" type="button">Display</button>

and I'd like to click automatically that button every 100ms, I wrote this script but it doesnt work:我想每 100 毫秒自动单击一次该按钮,我编写了这个脚本,但它不起作用:

window.onload = function(){
  var button=document.getElementsByClassName("btn btn-primary");
  setInterval(function(){ 
    button.click();
  }, 100);
)

getElementsByClassName return a NodeList instead of an Element . getElementsByClassName返回NodeList而不是Element Try to use querySelector尝试使用querySelector

window.addEventListener('load', function () {
  var button = document.querySelector(".btn.btn-primary");
  setInterval(function () { 
    button.click();
  }, 100);
});

If you want apply with all matched buttons, you can use querySelectorAll and [].slice.call to convert NodeList to Array如果要应用所有匹配的按钮,可以使用querySelectorAll[].slice.callNodeList转换为Array

window.addEventListener('load', function () {
  var buttonList = document.querySelectorAll(".btn.btn-primary");
  var buttons = [].slice.call(buttonList);
  setInterval(function () { 
    buttons.forEach(function (button) {
        button.click();
    });
  }, 100);
});

Many selectors can yield multiple results, so you must specify an index to work with a selected element.许多选择器可以产生多个结果,因此您必须指定一个索引才能使用选定的元素。 If there is only one result the index will be [0].如果只有一个结果,则索引将为 [0]。

window.onload = function(){
  var button=document.getElementsByClassName('btn btn-primary')[0];
  setInterval(function(){ 
    button.click();
  }, 100);
}

Also if this script runs before your button has loaded, the selector will not yield any results and could produce an error - here is one solution for that:此外,如果此脚本在您的按钮加载之前运行,则选择器不会产生任何结果并可能产生错误 - 这是一种解决方案:

window.onload = function(){
  setInterval(function(){
    if (typeof document.getElementsByClassName('btn btn-primary')[0]!="undefined"){
        document.getElementsByClassName('btn btn-primary')[0].click();
    }
  }, 100);
}

The above script will repeatedly check whether the selected element is defined before clicking it (then continue to do so indefinitely since you don't have any mechanism to toggle it off).上面的脚本将在单击之前反复检查所选元素是否已定义(然后无限期地继续这样做,因为您没有任何机制可以将其关闭)。 You also had a ")" at the last line of your sample code which I think should have been a "}".您的示例代码的最后一行还有一个“)”,我认为它应该是一个“}”。

For making a button click automatically, it is better to pass the function in setInterval Method .为了使按钮自动单击,最好在setInterval Method中传递 function 。

 setInterval(function(){ alert('Working fine'); //Same function as it was supposed on click }, 5000);

To see the working model, I have attached a JS Fiddle to it.为了查看有效的 model,我附上了一个 JS Fiddle。 https://jsfiddle.net/xrefwqcj/2/ https://jsfiddle.net/xrefwqcj/2/

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

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