addEventListener pass caller as argument

Posted by Ryan on Stack Overflow See other posts from Stack Overflow or by Ryan
Published on 2010-04-18T15:59:58Z Indexed on 2010/04/18 16:03 UTC
Read the original article Hit count: 207

Hi,

I have the following code. And my problem is that when clicking, the event is firing but the argument passed is not the correct one. It is passing the last dynamically created row i.e. dataStructure.length value. Anyone knows a solution how to get around this?

        var table = document.getElementById('output');                  

        for(i =0; i<dataStructure.length; i++){
            var row = document.createElement('tr');
            row.setAttribute('id', i);
            var url = dataStructure[i].url;

            if(document.addEventListener)
                row.addEventListener('click', function(){handleRowClick(i);}, false);
            var obj = dataStructure[i];
            var cellCount = 0;
            for(field in obj){
                var cell = document.createElement('td');
                cell.setAttribute('id', cellCount++);
                //cell.addEventListener('click', function(){window.open(dataStructureObj.links[i].url);}, false);
                cell.innerHTML = obj[field];
                row.appendChild(cell);
            }
            cellCount = 0;
            table.appendChild(row);
        }           
        }

        function handleRowClick(rowClicked){
            var rowHTML = rowClicked.innerHTML;
            var cells = rowHTML.getElementsByTagName('td');
            for(cell in cells)
            {
                alert(cell.value);
            }
            window.open(cells[1].innerHTML); 
        }

© Stack Overflow or respective owner

Related posts about javascript-events

Related posts about JavaScript