简体   繁体   中英

Scope within jQuery click handler

I have a function where I get some data, and insert it into a row of a table.

I then set up a click event on the row so that when it is clicked, it navigates to a URL specified in my data object:

$(data).each(function(i, item) {

    var row = $("<tr></tr>");
    tbody.append(row);

    // Add some cells into the row...
    var firstNameCol = $("<td>" + item.FirstName + "</td>");
    row.append(firstNameCol);

    // Set up click handler
    row.click(function() {
       window.location.href = item.DetailsURL;
    });
 });

Now this code works fine, but it has made me realise that I'm not sure how the events work.

The function contains a reference to item , which is a variable local to my for loop of items. When the user clicks on the row, how does it know which item it is looking at? Is it somehow cached when the click function is registered?

Secondly, is this method really bad? Am I forcing it to do a load of work behind the scenes?

item is a variable that's available in that scope when you bind , so that anonymous function you're passing into the .click() function just gets a copy of it (or reference if it's an object) at that time .

You could call this "cached", sure, but it's just a reference or a variable copy it gets at that point. .each() creates a closure, the callback function that you pass it ( function(i, item) {...} ), and inside there (depending on if it's an object or not, in that case you get the same reference) you get your own copy for that iteration of the loop.

As for performance, this isn't a "load of work" really, it's perfectly normal.

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