javascript - Why does my anonymous function not have the context of the current object in this example? -
when run sample code in google chrome, intended behavior--loading image within placeholder image tag on current page--does not occur. checked value of currpic when showpic() called, , "undefined." know if change parameter showpic 'anchors[i]' 'this', work, trying understand why so.
function showpic(currpic) { var srcloc = currpic.getattribute("href"); var placeholder = document.getelementbyid("placeholder"); placeholder.setattribute("src", srcloc); var imglabel = document.getelementbyid("imglabel"); var currlinktitle = currpic.getattribute("title"); imglabel.firstchild.nodevalue = currlinktitle; } function preparegallery() { if(!(document.getelementsbytagname && document.getelementbyid)) return false; var imggallery = document.getelementbyid("imagegallery"); if(imggallery) { var anchors = imggallery.getelementsbytagname("a"); var i; for(i = 0; < anchors.length; i++) { anchors[i].onclick = function() { showpic(anchors[i]); return false; } } } }
inside anonymous function, anchors[i] provides runtime reference. @ time click occurs, anchors[i] no longer exists. while existed @ time assignment made, falls out of scope @ time of click (since it's array reference). however, using this provides solid reference immediate object available @ time of click.
more succinctly, anchors[i] reference position in array (which leaves scope once loop exits). this reference dom element itself.
Comments
Post a Comment