SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    Jun 2006
    Location
    Durban, South Africa
    Posts
    287
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Passing HTML objects to dynamically created functions

    Hi all

    I am having a small problem with passing HTML objects to dynamically created functions.
    Here is some of my code below.

    Code:
    add_event(elm , 'click' , new Function("temp(" + elm + " , " + elm2 + ");"));
    Basically im trying to add a click event to an element, and then pass that element, and another element, to a function so I can use them.

    When I try click that element, I get this error message in FF

    Missing ] after element list
    temp([object HTMLInputElement]);

    I think whats happening is, when JS sends the variable to the function, its sending it as a string, and not the actual element.

    Iv also tried this way

    Code:
    add_event(elm , 'click' , function _temp() {temp(elm , elm2);});
    But this code is in a for loop, and elm and elm2 change every time, but if I click on any of the elements, the temp function has the elm and elm2 values for the last iteration of the for loop.

    Can anyone help me with my problem.
    Much appreciated
    Bye

  2. #2
    SitePoint Evangelist
    Join Date
    Jul 2007
    Posts
    345
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The loop problem is probably due to a closure being formed by a nested function. Try something like
    Code:
    for (var i = 0; i < whatever; i++){
       (function(i){
          add_event(elm , 'click' , function() {temp(elm[i] , elm2[i]);});
       })(i);
    Take a look at http://www.room51.co.uk/js/articles/...uresPart1.html

  3. #3
    SitePoint Addict
    Join Date
    Jun 2006
    Location
    Durban, South Africa
    Posts
    287
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks bro, this looks like what im looking for.
    Thanks for your help


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
  •