JavaScript don't execute if statement -
i have loop , when execute code execute 'else' statement not if statement.
screenshot:
i recommend using dom dataset save index of picked color instead of color itself.
var colors=["rgb(99,49,25)","rgb(115,152,170)","rgb(195,171,20)","rgb(55,49,35)","rgb(177,134,98)","rgb(247,100,160)"] var squares = document.queryselectorall(".square"); var colordisplayed = document.queryselector("#colordisplayed"); var pickedcolor = 0; colordisplayed.innertext = colors[pickedcolor] var handler = function(e) { var clickedcolor = number(e.target.dataset.colorindex); // explicitly transform dataset colorindex number if (clickedcolor === pickedcolor) { // if don't want transforming, use `==' instead of `===' alert("right"); } else { alert("wrong"); } } (var = 0; < squares.length; i++) { squares[i].style.background = colors[i]; squares[i].dataset.colorindex = i; squares[i].addeventlistener("click", handler) }
.square {width: 100px;height: 100px;border: solid 1px black;float: left;}
<div id="colordisplayed"></div> <div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div> <div class="square"></div></div>
another way using closure save it.
var colors=["rgb(99,49,25)","rgb(115,152,170)","rgb(195,171,20)","rgb(55,49,35)","rgb(177,134,98)","rgb(247,100,160)"] var squares = document.queryselectorall(".square"); var colordisplayed = document.queryselector("#colordisplayed"); var pickedcolor = 0; colordisplayed.innertext = colors[pickedcolor] (let = 0; < squares.length; i++) { // notice keyword `let' here squares[i].style.background = colors[i]; squares[i].dataset.colorindex = i; squares[i].addeventlistener("click", function() { if (i === pickedcolor) { // since "letted", different each in each event listener function alert("right"); } else { alert("wrong"); } }) }
.square {width: 100px;height: 100px;border: solid 1px black;float: left;}
<div id="colordisplayed"></div> <div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div> <div class="square"></div></div>
Comments
Post a Comment