SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Jun 2006
    Posts
    13
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Lightbulb Passing dynamic arguments to a function

    For example, have 5 images, I want to assign in dynamic way onclick events to each, on click on any image, alert the order of that image.

    Code:
    var imgs = document.getElementsByTagName('img');
    
    for (var i=0; i < imgs.length; i++ ) {
       imgs[i].onclick = function(){ alert(i); };
    }
    On click on any image, I'll get the number of last value of "i" var, if 5 images, I'll get 5, at any image click.

    ----

    Here is my solution to this problem, to eval the function with proper args.

    Code:
    var imgs = document.getElementsByTagName('img');
    
    for (var i=0; i < imgs.length; i++ ) {
       eval ('f=function(){ alert('+i+'); }');
       imgs[i].onclick = f;
    }
    Works fine under FF&IE, but it look to me soooooo ugly.
    Your solutions to this, please.

  2. #2
    SitePoint Wizard chris_fuel's Avatar
    Join Date
    May 2006
    Location
    Ventura, CA
    Posts
    2,751
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ahh, you've reached the ever fun and exciting issue of variable closure:

    http://www.sitepoint.com/forums/showthread.php?t=384797

    See item #6 for more details.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •