javascript - Closures and ClickEvent Listener inside Iterator -
i know method of wrapping anonymous function in parentheses , calling right away called iife (immediately-invoked function expression, pronounced "iffy").
the script below iterate on cats object , dynamically allocate cat images,names , number of clicks on every image inside container.
var cats = [{ path: "img/cat.jpg", name: 'lazy cat', click :0 }, { path: "img/cat.jpg", name: 'shy cat', click :0 } ] (var = 0; < cats.length ; ++) { //generating container every cat var containerid = "cat-container"+ i; //caching property value every cat var catname = cats[i].name; var imgpath = cats[i].path; var clickid = "click"+i; var imageid = "cat"+i; //append these property in dom $('.left-container').append('<div id ="'+containerid+'">'); $('#'+containerid+'').append('<p>'+catname+'</p>'); $('#'+containerid+'').append('<p id = "'+clickid+'">'+cats[i].click+'</p>'); $('#'+containerid+'').append('<img id ="'+imageid+'"src ="'+imgpath+'">'); //targeting elements id $('#cat'+i+'').click( (function(icopy) { return function() { //increment click value. cats[icopy].click++; //add value on inside <p> element. $('#click'+icopy+'').text(cats[icopy].click); } })(i)); }
it works need understand point
the loop iterate (2 times here) , after user interact page clicking on image how event listener handler value of required parameter such i , icopy. makes sense me click event must during execution time of loop pass both parameters i , icopy .
i confused that.
Comments
Post a Comment