Hi I am struck with this problem.
I need to create a table with Onclicklisteners dynamically. so i prefered this way.
function create_weekmenu(json) { var column_list=json.week_list; var menu_table=document.getElementById("weekmenu"); var row=document.createElement('tr'); for(var i=0;i<column_list.length;i++) { var cell=document.createElement('th'); var span_ele=document.createElement('span'); if(span_ele.addEventListener) { span_ele.addEventListener('click', toggletable(column_list[i]),true); } else if(span_ele.attachEvent) { // IE < 9 :( span_ele.attachEvent('onclick', toggletable(column_list[i])); } span_ele.appendChild(document.createTextNode(column_list[i])) cell.appendChild(span_ele); row.appendChild(cell); } menu_table.appendChild(row); }
The Resultant element Structure I am getting is
<table id="weekmenu">
<tr>
<th>
<span>week_one</span>
</th>
<th>
<span>week_two</span>
</th>
</tr>
</table>
But i need a Element Structure like this,
<table id="weekmenu">
<tr>
<th>
<span onclick="toggle(week_one)'>week_one</span>
</th>
<th>
<span onclick="toggle(week_two)'>week_two</span>
</th>
</tr>
</table>
Further to notice: I could see that the onclick listener is triggering while creating the element. but its not binding with the element permanently.
What would be the solution.
I prefered to construct DOM structure using appendChild() than by .innerHTML or document.write().
clicklistener withaddEventListener/attachEventwould not create anonclick="toggle(week_one)'on the element, why do you need it that way?