简体   繁体   中英

How to track clicks of a button?

I'm trying to track the clicks on a button on my website. I've tried adding the following but to no success. I'm a noob to JS..

function trackButton(e) {
    onPage.innerHTML = ++i;
}

var i = 0;
var onPage = document.getElementById(‘track’);
var clickCount = document.getElementById(‘bttn’);
clickCount.addEventListener('click', function (e) {
    addOne(e);
}, false); 

You did some mistake:

  1. The function addOne doesn't exist, it's trackbutton
  2. it's i++ to increment a value, not ++i

And some tips for you:

  1. Use let and const (ES6) for the variable, not var
  2. And the e for the event is useless here, you are not using it, so it's not mandatory here

Do these change and it must work !

UPDATE:

  1. To increment a value ++i works, see the documentation
  2. Change the quotes '' with " " or ' ' .
    Like so: document.getElementById('track') to document.getElementById('track')

I was checkin your code and its almost all right, i think that the problem its in your addOne function, here is a way to resolve the problem. i creat the button and paragraph elements in html and in javascript a variable n where we are going to storage the clicks tha the user did and we increment n when the function its called in the button's event

 var n = 0; var button = document.getElementById('track'); button.addEventListener('click', trakeo); var texto = document.getElementById('number'); function trakeo(){ n++ texto.innerHTML = n; }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>A Great Demo on CodePen</title> </head> <body> <button id="track">Button</button> <p id="number"></p> </body> </html>

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