Debt Consolidation - Human body - Computer Jobs - Debt Consolidation - Property in Brazil

PDA

View Full Version : Javascript multiple created rows and event listeners


rickvb
Aug 19th 2008, 1:40 am
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);
}
}

rohan_shenoy
Aug 19th 2008, 8:57 am
Workaround: Use some attribute to hold the value of var p. Just in case you need detailed guidance, I just wrote a entry (http://www.w3hobbyist.com/javascript-ajax/variable-holds-last-value-when-added-to-event-listener/) 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. :)

rickvb
Aug 19th 2008, 9:20 am
Great! Just what I needed. Thanks ;)