Monday, March 31, 2008

dom nodes + for-loops THAT WORK

Imagine you have a collection of DOM nodes (html element nodes, whatever you want to call them) stored in the variable ‘elements’, and that var len = elements.length. The following for-loop will not work. Every element will have an onclick event handler function that calls clicked(len) – not the respective clicked(i)



WRONG

    for( var i = 0; i < len; i++){
        
        var el = elements[i];
        el.addListener('click', function(){clicked(i);}, false);
        
    }



RIGHT

    (function loop( I ){
        if (I == len) return;
        var i = I;
        
        
        var el = elements[i];
        el.addListener('click', function(){clicked(i);}, false);
        
        
        loop(++I);
    })(0);

Note: addListener is not any browser’s implementation. It’s just my way of saying addEventListener (or, for IE, attachEvent). Also, for brevity, the function ‘clicked’ is not here defined. Yes, this is documented in a couple places around the web. But those places are not obvious or easily searchable for everyone.

No comments:

Post a Comment