计算使用click()函数的次数

时间:2018-11-25 13:58:50

标签: javascript

我想知道click()函数已经使用了多少次并记录下来,但是我总是收到称为“ undefined”或“ NaN”的错误

var sleep = 1000;
var run = setInterval(function() {
  var span = document.getElementsByTagName("span");
  for (var i = 0; i < span.length; i++) {
    if (span[i].textContent != "danger") {
      var jump = document.getElementsByClassName("jump")[0].click();
      console.log(jump++);
    } else {
      clearInterval(run);
    }
  }
}, sleep);
<span>Danger</span>
<button type="button" class="jump">Click</button>

2 个答案:

答案 0 :(得分:2)

您需要定义跳转,而不要为其分配按钮
我也建议使用querySelector(All)代替getElementsByClass / TagName

var sleep = 1000, jump=0, jumpBut = document.querySelector(".jump");
var run = setInterval(function() {
// move this var outside the loop if the spans never change in number
  var span = document.querySelectorAll("span"); 
  for (var i = 0; i < span.length; i++) {
    if (span[i].textContent != "danger") {
      jumpBut.click();
      console.log(jump++);
    } else {
      clearInterval(run);
    }
  }
}, sleep);
<span>Danger</span>
<button type="button" class="jump">Click</button>

但是请尝试执行此操作-在按钮上添加click事件监听器,并将其添加到计数器中

var sleep = 1000, jump=0, jumpBut=document.querySelector(".jump");
jumpBut.addEventListener("click",function() {
  jump++,
  console.log(jump)
})
var run = setInterval(function() {
  var span = document.querySelectorAll("span");
  for (var i = 0; i < span.length; i++) {
    if (span[i].textContent != "danger") {
      jumpBut.click();
    } else {
      clearInterval(run);
    }
  }
}, sleep);
<span>Danger</span>
<button type="button" class="jump">Click</button>

答案 1 :(得分:1)

您需要一个计数器变量! 另外,除非您的DOM元素不断变化,否则不必每次都调用getElementsByTagName

var sleep = 1000;
var counter = 0;
var spans = document.getElementsByTagName("span");
var jump = document.getElementsByClassName("jump")[0];

var run = setInterval(function(){        
    for (var i =0; i< spans.length; i++) {
        if (spans[i].textContent != "danger") {
            jump.click();
            counter++;
            console.log(counter);
       } else {
            clearInterval(run);
       }
    }
}, sleep);