var DAYBOOK = {
22 : 'hmm',
9 : 'waaaah'
};
function cnstr_submenu(){
var elm = $('#test');
for(var key in DAYBOOK){
(function(key){
elm.append('<a href="#">'+DAYBOOK[key]+'</a><br>').click(function(){
alert(key);
});
})(key);
}
};
cnstr_submenu();
Why is it that all properties in the DAYBOOK object is alerted when you click a link?
elm.append(...).clickwill in fact bind theclickto theelm(thediv). So when clicking a link, the link doesn’t do much – rather the click handlers of thedivare executed, which has had a function bound forclicktwice.If you want each link to alert one value, bind the function to the link instead: