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

  • SEARCH
  • Home
  • 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 6184369
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T01:31:35+00:00 2026-05-24T01:31:35+00:00

The following page displays five buttons, clicking each button gets alert ‘5’. I want

  • 0

The following page displays five buttons, clicking each button gets alert ‘5’. I want when I click the first button, I get alert ‘1’, the second button ‘2’ …etc.

<!doctype html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    </head>
    <body>
        <div id="nums"></div>
        <script type="text/javascript">
            var nums = [1,2,3,4,5];
            for(var i in nums){
                var num = nums[i];
                var btn=$('<button></button>').text(num).click(function(){alert(num);});
                $('#nums').append(btn);
            }
        </script>
    </body>
</html>
  • 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-05-24T01:31:35+00:00Added an answer on May 24, 2026 at 1:31 am

    The event handler functions you’re creating in the loop have an enduring reference to the variables in scope where they’re created, not a copy of those variables as of when the function was created. This is how closures work (more: Closures are not complicated). So all of your handler functions refer to the same num variable, and they refer to it as of when the click event occurs. Since at that point it’s 5 (the last value it was ever assigned), you end up with all of them alerting 5.

    If you want the event handler to refer to num as of when the handler was created, you have to have the handler close over something that won’t change. The usual way is to have a function that builds your handler function, and have the handler function close over an argument to that builder function:

    var nums = [1,2,3,4,5];
    for(var i in nums){
        var num = nums[i];
        var btn=$('<button></button>').text(num).click(buildHandler(num));
        $('#nums').append(btn);
    }
    
    function buildHandler(val) {
        return function(){alert(val);};
    }
    

    As you can see, we call buildHandler when hooking the click event and pass its return value into click. buildHandler creates and returns a function that closes over val, the argument we pass to it. Since val is a copy of the number we want it to alert, and nothing ever changes val, the functions perform as desired.


    Off-topic 1: You’re creating a lot of global variables in that code. The global namespace is already very crowded, I recommend avoiding creating more globals whenever you can avoid it. I’d wrap that code in a function so that the varibles are all local to that function:

    <script>
        (function() {
            var nums = [1,2,3,4,5];
            for(var i in nums){
                var num = nums[i];
                var btn=$('<button></button>').text(num).click(buildHandler(num));
                $('#nums').append(btn);
            }
    
            function buildHandler(val) {
                return function(){alert(val);};
            }
        })();
    </script>
    

    It does the same thing (we define the function, then call it immediately), but without creating global i, num, nums, and btn variables.


    Off-topic 2: You’ve used for..in with an array without doing any checks to make sure you’re only dealing with array indexes. for..in does not loop through array indexes; it loops through object property names. Writing for..in loops as though they looped through array indexes will bite you at some stage. Just use a normal for loop or do the necessary checks or use jQuery’s each function. More: Myths and realities of for..in

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

Sidebar

Related Questions

My page displays divs containing posts. The divs have the following format (where you
My page displays posts stored in my database and pairs a like/dislike button to
My asp.net page dynamically displays 207 questions (I can't control this). Each question have
The page displays fine in the following: Chrome 21 on OSX FireFox 14 on
I have the following code which displays the user's zipcode on the page (if
My HTML page displays an image with the following code (using Flickr) <?php echo
The following code is not working as the page displays nothing, and I am
I have a page that displays a default image using the following code: echo
I have the following web page, which displays a number of images and a
the following code is for user control(it display banner), the page get stuck in

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.