简体   繁体   中英

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 menuLinks.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM