0

I have implemented a menu with jQuery where the items and the functions are assigned dynamically. This code works.

But since I need to hide the menu when the option is clicked, I changed

p.click(funcs[i].f);

to

p.click(function(){
    menu.hide();
    funcs[i].f;
});

as in here,but I get Uncaught TypeError: Cannot read property 'f' of undefined because the variable i is out of bounds. how to fix this code?

ps0604
  • 1,227
  • 23
  • 133
  • 330

2 Answers2

0

Try this :

        (function(idx) {
            p.click(function(){
                menu.hide();
                funcs[idx].f();
            });
        })(i);
laruiss
  • 3,780
  • 1
  • 18
  • 29
0

I'd suggest:

for (var i = 0; i < len; i++) {

    (function(i){$('<p />', {
        'style' : 'cursor: pointer',
        'text' : funcs[i].title,
        'click' : function(){
            funcs[i].f();
            menu.hide();
        }
    }).appendTo(menu)})(i);
}

JS Fiddle demo.

The above passes the i variable into the inner scope, and uses a slightly different (due to personal preference) approach to create the <p> elements.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • Thanks, this works, could you clarify `inner scope`? – ps0604 Oct 05 '14 at 16:02
  • I genuinely wish I could, but I don't honestly understand it myself. I *think* I do, sometimes, but then I try and construct an explanation and I fall into self-contradictory attempts and metaphors. So, all I can really do is point you to the explanation in this answer: http://stackoverflow.com/a/9054695/82548 and apologise for the lack of useful information here. – David Thomas Oct 05 '14 at 16:18
  • "In JavaScript, scope is the set of variables, objects, and functions you have access to. JavaScript has function scope: The scope changes inside functions." (From W3school) So what David Thomas is saying is that inside the function, `i` is not the same as `i` outside the function (i.e. the `i` of the first line and the last line of his code), hence its "inner scope". It would be simpler to explain if in @DavidThomas 's code the parameter of the function was named with another letter (j or k, for example, or even `inner_i` ;-) ). – laruiss Oct 05 '14 at 16:46