clarkk
clarkk

Reputation: 1

a href click() and closure

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();

http://jsfiddle.net/9AqVK/

Why is it that all properties in the DAYBOOK object is alerted when you click a link?

Upvotes: 0

Views: 126

Answers (2)

ShankarSangoli
ShankarSangoli

Reputation: 69915

Try this

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>').click(function(){
                alert(key);
            }).append("<br />");
        })(key);
    }
};
cnstr_submenu();

Upvotes: 0

pimvdb
pimvdb

Reputation: 154918

elm.append(...).click will in fact bind the click to the elm (the div). So when clicking a link, the link doesn't do much - rather the click handlers of the div are executed, which has had a function bound for click twice.

If you want each link to alert one value, bind the function to the link instead:

elm.append( // append the following element
    // create a link with a click handler bound
    $('<a href="#">'+DAYBOOK[key]+'</a><br>').click(function(){
            alert(key);
    })
);

Upvotes: 5

Related Questions