Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8797715
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T23:54:35+00:00 2026-06-13T23:54:35+00:00

If I create a bunch of objects in a loop like so: for(var i

  • 0

If I create a bunch of objects in a loop like so:

for(var i = 0; i < 5; i++)
{
    var data = { val: i * 2 };
    var obj = $('<li>Item</li>');

    $("ul").append(obj);

    obj.click(function()
    {
        alert(data.val);
        // Output is 8 for all items.

    });
}

I am only able to access the last created data object within the .click() handler.

How can I refer to the relevant data object within my handler – the one that was created at the same time as the jQuery object being clicked?

I’ve been able to get around this in the past by assigning random attributes on the jQuery object via .attr() to hold data, rather than a separate object, but I’d like to move away from that approach.

I’ve also tried this but with no luck:

var data = { val: i * 2 };
var obj = $('<li>Item</li>');

obj.data = data;

obj.click(function()
{
    // 'data' is undefined here i.e. not associated with $(this).
    alert($(this).data.val);

});
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T23:54:37+00:00Added an answer on June 13, 2026 at 11:54 pm

    The problem with the first example is obscured by the scope of the variables. In JS all variables have function scope so rewriting the code to show that more explicitly would result in:

    var i,data,obj;
    for(i = 0; i < 5; i++) {
        data = { val: i * 2 };
        obj = $('<li>Item</li>');
    
        $("ul").append(obj);
        obj.click(function() {
            alert(data.val);
        });
    }
    

    Now it’s more obvious that data inside the loop is just one variable and not a new for each iteration (as in would be in Java, C# and the like). The anonymous function passed as the click handler uses this variable, it closes over it. The result of that is that the current value of the variable when the function is executed is used, not the value the variable had when the function is assigned as a click handler.

    To get around this you can either attach the data to the element itself.

    In your code you do obj.data = ... however that attaches the value to the selection and not the element. Next time you select the same element you have a new object without the data.property. Instead you can use the jQuery .data() method.

    obj.data('key',data);
    obj.click(function() {
        alert($(this).data('key').val);
    });
    

    or if you would want to embed the value into the function you can do that with a self executing function. When you pass the variable as an argument to a function you are using the current value instead of closing over the variable.

    var i,
        data,
        obj,
        createClick = function(data) {
            return function(){
               alert(data.val);
            };
        };
    for(i = 0; i < 5; i++) {
        data = { val: i * 2 };
        obj = $('<li>Item</li>');
    
        $("ul").append(obj);
        obj.click(createClick(data));
    }
    

    Note
    As an aside you should get into the habit of putting { at the end of a line not the begining. Semi colon insertion can have some unexpected results if { is on the next line.
    E.g

    return 
        {
          val : 1
        }
    

    might return undefined because a semi colon might be inserted after return ignoring the object literal

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to create an object to hold a bunch of properties like var
In my code I want to create a bunch of objects of a class
Specifically, if I use NInject to create a bunch of objects that have been
I have a parent Obj-C object containing (in a collection) a bunch of objects
I created jQuery function that gets bunch of simple objects that contains id and
I have create a bunch of .o files (via gcc -c $file.c $someotherops -o
I want to create a bunch of errors. each specific to its own class
If you create a bunch of heatmaps: for i=1:10 HeatMap(rand(5,5)) end then you're left
I want to create a helper screen that can create a bunch of Django
I have a C# WPF application where I need to create a bunch of

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.