Why onclick doesn't work on that div?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
8 views
All good time!The problem is:
Cycle create div's on the page and at the end of it hung the processor.
by clicking on the div it should change the content, but the problem is that when I click on the desired block, the content always changes only the last block.Although as I understand it weighs a click handler on all the blocks and it needs to change the content on I need. What's the problem?
field


[data-view = "pole"] { width: 200px; height: 200px; background-color: rgb(80, 168, 190); float: left; margin: 2px; } .pole-blue { background: rgb(180, 70, 180); }

var home = document.getElementById('home'); for(var i = 0;i<10;i++) { var pole = document.createElement('div'); pole.dataset.item = i; pole.dataset.view = "pole"; home.appendChild(pole); pole.onclick = function() { if(this.className != 'pole-blue') { pole.className = 'pole-blue'; } } }
by | 8 views

1 Answer

0 like 0 dislike
Because the element on which the event occurred, you need to go through e.target, that is, to use the event descriptor e.
pole.onclick = function(e) { if(e.target.getAttribute('class') != 'pole-blue') { e.target.setAttribute('class', 'pole-blue'); } }

Another point, using the variable var must be declared once, using var to override impossible.
var pole = null; for(var i = 0;i<10;i++) { pole = document.createElement('div');
by

Related questions

0 like 0 dislike
2 answers
0 like 0 dislike
1 answer
asked May 1, 2019 by etozhetisachniy
0 like 0 dislike
2 answers
0 like 0 dislike
1 answer
110,608 questions
257,186 answers
0 comments
35,457 users