Javascript multiple created rows and event listeners

Discussion in 'JavaScript' started by rickvb, Aug 19, 2008.

  1. #1
    Dear reader,

    I'm creating a button for table row adding (0-99 rows).
    I add these rows with a for loop.
    The textnodes and styles apply just fine.
    But there's a problem when I try to add more than 1 eventlistener to multiple rows and stick a function to it.
    The problem is : somehow it only uses the function+arguments added in the last row for all the row columns td1

    Here's my code

    
        for(var p=1;p<ond.length;++p){
        if(typeof(ond[p])!='undefined'&&ond[p]!=''){
        var tbody = document.getElementById(hk).getElementsByTagName("TBODY")[0];
        var delim=ond[p].split("[&]");
        var row = document.createElement("TR");
    
        var td1 = document.createElement("TD");
        td1.style.padding="0px 0px 0px 22px";
        td1.style.textAlign="left";
        var poon=delim[6].substr(0,1);
        if(poon!='0'){
    
        if(td1.addEventListener){
        td1.addEventListener('click',function(){selpos(unescape(delim[1]),url,delim[0])},false); // <-- I made sure these arguments are different every time..
        }else if(td1.attachEvent){
        td1.attachEvent('onclick',function(){selpos(unescape(delim[1]),url,delim[0])}); <-- I made sure these arguments are different every time..
        }
        td1.style.cursor="pointer";
        td1.style.background="url('img/ggs.png') no-repeat";
        }else{
        td1.style.background="url('img/ggt.png') no-repeat";
        }
    
        td1.appendChild(document.createTextNode(unescape(delim[1])));
        td1.style.borderTop="1px solid #ececec";
        row.appendChild(td1);
        tbody.appendChild(row);
    }
        }
    Code (markup):
     
    rickvb, Aug 19, 2008 IP
  2. rohan_shenoy

    rohan_shenoy Active Member

    Messages:
    441
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    60
    #2
    Workaround: Use some attribute to hold the value of var p. Just in case you need detailed guidance, I just wrote a entry for you. Even I was in a similar situation and it took me 6 hrs for this to strike.
    Also, there is a small request at the end of the entry. Please try to help me in return. :)
     
    rohan_shenoy, Aug 19, 2008 IP
  3. rickvb

    rickvb Active Member

    Messages:
    157
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    53
    #3
    Great! Just what I needed. Thanks ;)
     
    rickvb, Aug 19, 2008 IP