开发者

Jquery Scope Issue

I can't figure out this scope issue:

var menuLinks = new Array("about.php", "contact.php");
function setClickListeners()
{
    for(var i=0; i<menuItems.length; i++)
    {
        $("#" + menuItems[i]).click( function () {
            window.alert(menuLinks[i]);
        });
    }
}

Notes: menuItems and menuLink is the same length. This code is stripped down to make understanding it easier.

The outcome of this code when an item is clicked is an alert "undefined". It should be the data from menuLi开发者_运维百科nks.

Help!!!!

Frankie


for (var i=0; i < menuItems.length; i++) {
    (function(i) {
         $("#"+menuItems[i]).click(function() {
              alert(menuLinks[i]);
         });
    }(i));
}

You need to make the current value of i local to your anonymous function in .click.

JavaScript only has function scope. So if you don't make i local then whenever you press click the value of i is the current value which in this case is menuItems.length - 1.

What your doing above is creating a new functional scope and passing the value of i into it so that the current value of i stays constant in that function scope. That way your click function picks up the constant value of i from the closure.

jslint

Let's over complicate the code and satisfy jslint.

var wrapper = function(i) {
    $("#"+menuItems[i]).click(function() {
         alert(menuLinks[i]);
    });
};

for (var i=0; i < menuItems.length; i++) {
    wrapper(i);
}


A cleaner code:

var menuLinks = new Array("about.php", "contact.php");
function setClickListeners()
{
    $.each(menuLinks, function(i, element)
    {
        $("#" + menuItems[i]).click( function (e) {
            alert(menuItems[i]);
            e.preventDefault();
        });
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜