简体   繁体   中英

Counting how many times the click() function has been used

I would like to know how many times the click() function has been used and log that but I always get the error called "undefined" or "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> 

You need to define jump and not assign the button to it
Also I recommend to use querySelector(All) instead of 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> 

But try this instead - add a click event listener to the button and have that add to the counter

 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> 

You need a counter variable! Also, you don't have to use getElementsByTagName every time the interval is called, unless your DOM elements keep changing.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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