javascript - Add click count inside an object inside an array -
i trying count number of clicks triggered user on each image. click count stored in object, inside array. how can this?
var clicks = 0; var gatas = []; gatas[0]= {img : "img/ml.jpg", clicks : 0}; gatas[1]= {img : "img/ma.jpg", clicks : 0}; (var = 0; < gatas.length; i++) { var elemimg = document.createelement("img"); elemimg.src = gatas[i].img; var elemclick = document.createelement("h3"); //add +1 every time user clicks image, storing count in //object elemclick.textcontent = gatas[i].clicks; document.body.appendchild(elemclick; document.body.appendchild(elempic); };
you have bind click
event handler every image.
also, don't forget use let
keyword in order declares block scope local variable.
variables declared let
have scope block in defined, in contained sub-blocks. in way, let
works var
. main difference scope of var variable entire enclosing function.
this problem found in closures.
var clicks = 0; var gatas = []; gatas[0]= {img : "img/ml.jpg", clicks : 0}; gatas[1]= {img : "img/ma.jpg", clicks : 0}; let elemimg=[]; let elemclick=[]; (let = 0; < gatas.length; i++) { elemimg[i] = document.createelement("img"); elemimg[i].src = gatas[i].img; elemclick[i] = document.createelement("h3"); elemclick[i].textcontent = gatas[i].clicks; elemimg[i].onclick=function(){ gatas[i].clicks++; elemclick[i].textcontent = gatas[i].clicks; }; document.body.appendchild(elemclick[i]); document.body.appendchild(elemimg[i]); };
Comments
Post a Comment