variables - Scope, closures and bindings in javascript. Why is my loop not working correctly? -
i trying create list when li element clicked, specific div displayed. want read id of div , other properties dictionary. so, dictionary looks this:
var ifsrc = {"welcome":"welcome.html", "proceduresandcomputers":"../proceduresandcomputers/index.html", "someid":"../somesourcefileforaniframe"}
and function form li elements
function createmenu(){ var listy = document.getelementbyid("sidebar"); for(var key in ifsrc){ var elem = document.createelement('li'); elem.innerhtml = key; elem.classname = "unselected"; elem.addeventlistener("click",function(){opendiv(this,key);},false); listy.appendchild(elem); } listy.firstelementchild.classname="selected"; }
so, menu (ul li elements) looks ok, no matter li click on, opendiv function passes right value this
, same value key
. in particular, passes last value key
in ifsrc
dictionary. however, innerhtml of each elem (which set key
) appears fine. checked documentation addeventlistener , couldn't find much.
why happening? insights?
just make sure you're capturing correct key value (with closure, in example below). way have now, key
reference same value in of click events. can copy current value of key
each click event doing this:
elem.addeventlistener("click", (function(k) { return function() { opendiv(this, k); } })(key), false);
for reference -- check out "the infamous loop problem" explained here.
Comments
Post a Comment