I have an HTML table dynamically generated by js, and I want to add each row an onClick event.
Like this
(because of need to pass complex parameters in my original code, I use Javascript to add onclick function):
<!DOCTYPE html>
<html>
<body>
<table align="center" id="tableID" border="1" style="cursor: pointer;">
<thead>
<th>Text</th>
<th>MoreText</th>
<th>Lorem</th>
<th>Ipsum</th>
</thead>
</table>
<br />
<script type="text/javascript">
for (var i = 0; i < 4; i++) {
document.getElementById("tableID").innerHTML += '<tr><td>Text</td><td>MoreText</td><td>Lorem</td><td>Ipsum</td></tr>';
document.getElementById("tableID").rows[i+1].onclick = function () {
alert("Hello World");
//alert(i);
};
}
</script>
</body>
</html>
If the table row is fixed and declared in HTML document, using this method is working,
but in my code (dynamically generated table row), the onClick function only works in the last row.
I guess that maybe is asynchronous problem, but I can't figure out.
UPDATE
According to @Quentin's method, I edited my code. It works fine.
<!DOCTYPE html>
<html>
<body>
<table align="center" id="tableID" border="1" style="cursor: pointer;">
<thead>
<th>Text</th>
<th>MoreText</th>
<th>Lorem</th>
<th>Ipsum</th>
</thead>
</table>
<br />
<script type="text/javascript">
for (var i = 0; i < 4; i++) {
var table = document.getElementById('tableID');
var tr = document.createElement('tr');
tr.onclick = function () {
alert("Hello World");
};
var td1 = document.createElement('td');
td1.innerText = "Text";
var td2 = document.createElement('td');
td2.innerText = "MoreText";
var td3 = document.createElement('td');
td3.innerText = "Lorem";
var td4 = document.createElement('td');
td4.innerText = "Ipsum";
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
table.appendChild(tr);
}
</script>
</body>
</html>