A
A
Artem Petrenko2016-04-20 23:52:19
JavaScript
Artem Petrenko, 2016-04-20 23:52:19

Where is the error in the counter?

I get a collection of paragraphs. I want that on click on any, the number inside increases by one.
When I prescribe the number of the paragraph manually (fragment in the comment) - everything works. When you try to write a loop so that the number increases exactly in the paragraph on which you clicked, it does not work.
Most likely a child's mistake, but my eyes are blurred and I can't see. I will be grateful for help.

var byTag =  document.getElementsByTagName('p');

  for (var c = 0; c<byTag.length; c++) {
    byTag[c].onclick = function func () {
       byTag[c].innerHTML = ++counter;
    }
  }
  // byTag[0].onclick = function func () {
  // 	 byTag[0].innerHTML = ++counter;
  // }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nikolai Lapshin, 2016-04-21
@madmaker

for (var c = 0; c<byTag.length; c++) {
    byTag[c].onclick = function func () {
       byTag[c].innerHTML = ++counter;
    }
  }

Inside func(), the variable "c" appears to be undefined;
Check.
Before byTag[c].innerHTML = ++counter;
write console.log(c);
And look at the console - what it displays.

T
tsarevfs, 2016-04-21
@tsarevfs

See the end of the article .

var byTag =  document.getElementsByTagName('p');
var counter = 0

for (var c = 0; c < byTag.length; c++) {
   byTag[c].onclick = (function (num) {
      return function() {
         byTag[num].innerHTML = ++counter;
      }
   })(c)

The bottom line is that the variable "c" is global and is captured as a reference. That is, when onclic is called, its value == byTag.length and not what it was at the time the callback was added.

K
keslo, 2016-04-21
@keslo

Just put a handler on everything. Or hang a handler on the body and catch "event delegation". In it, you simply check, for example, for e.target.className and already change its contents through e.target.innerHTML.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question