#1
  1. /* Spawn Killer Killer */
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Nov 2004
    Location
    New Orleans, LA, USA
    Posts
    1,224
    Rep Power
    219

    Unobtrusive Javascript: add onclick function with a variable


    I'm trying to add an onclick event to some anchor elements using unobtrusive javascript. I want the onclick function to have a variable passed to it that references the row number.

    currently I have:
    Code:
    window.onload = function(){ //Wait for the page to load.
        var inout = document.getElementById('inout');
        var inoutTable = inout.getElementsByTagName('table').item(0);
        var rows = inoutTable.getElementsByTagName('tr');
        for(var i = 0; i < rows.length; i++){
        	current = rows.item(i);
        	deleteTd = document.createElement('td');
        	anchor = document.createElement('a');
        	anchor.href = "#";
        	anchor.setAttribute('onclick', 'deleteOut('+i+')');
    	anchor.appendChild(document.createTextNode("x"));
        	deleteTd.appendChild(anchor);
        	current.insertBefore(deleteTd, current.firstChild);
        }
    };
    which works great in firefox, but internet explorer doesn't recognize the setAttribute function. I tried replacing that line with:
    Code:
        	anchor.onclick = function(){deleteOut(i);};
    but this fails due to the fact that 'i' will hold the value of 'i' when it exits the for loop. What is a IE hating developer to do?
  2. #2
  3. CSS & JS/DOM Adept
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jul 2004
    Location
    USA (verifiably)
    Posts
    20,124
    Rep Power
    4309
    Use a closure.
    Code:
    anchor.onclick = (function(i){return function(){deleteOut(i);}})(i);
    http://blog.morrisjohns.com/javascri...es_for_dummies
    http://www.jibbering.com/faq/faq_notes/closures.html

    (Oy! I need to write up an answer to this FAQ and put it on my site.)

    Comments on this post

    • flashbck agrees
    Spreading knowledge, one newbie at a time.

    Learn CSS. | PHP includes | HTML Validator | CSS validator

    Remember people spend most of their time on other people's sites (so don't violate web design conventions).
  4. #3
  5. /* Spawn Killer Killer */
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Nov 2004
    Location
    New Orleans, LA, USA
    Posts
    1,224
    Rep Power
    219
    Thanks Kravvitz, I knew you'd have a solution for this annoyance. A kludge if I've ever seen one, but it works well!
    Originally Posted by Kravvitz
    (Oy! I need to write up an answer to this FAQ and put it on my site.)
    I would have found it had it been there

IMN logo majestic logo threadwatch logo seochat tools logo