/ Published in: JavaScript
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Javascript Event Delegation Test</title> <style type="text/css"> body { padding: 10px; } table { border: solid 1px black; } table td { padding: 3px; } </style> <script type="text/javascript"> window.onload = function() { // Old var rows = document.getElementById("old").getElementsByTagName("tr"); for (var i = 0, ln = rows.length; i < ln; ++i) { rows[i].onclick = function() { alert("Row Index: " + this.rowIndex); } } // New function getTarget(x){ x = x || window.event; return x.target || x.srcElement; } document.getElementById("new").onclick = function(e) { var root = this; var t = getTarget(e); while (t != root) { if (t.nodeName.toLowerCase() == "tr") { alert("Row Index: " + t.rowIndex); break; } t = t.parentNode; } }; }; </script> </head> <body> <strong>To test: Click on a table row.</strong> <h3>Attaching event to each row:</h3> <table id="old"> <tr> <td>One</td> <td>Two</td> <td>Three</td> </tr> <tr> <td>One</td> <td>Two</td> <td>Three</td> </tr> <tr> <td>One</td> <td>Two</td> <td>Three</td> </tr> <tr> <td>One</td> <td>Two</td> <td>Three</td> </tr> <tr> <td>One</td> <td>Two</td> <td>Three</td> </tr> </table> <h3>Attaching event to table:</h3> <table id="new"> <tr> <td>One</td> <td>Two</td> <td>Three</td> </tr> <tr> <td>One</td> <td>Two</td> <td>Three</td> </tr> <tr> <td>One</td> <td>Two</td> <td>Three</td> </tr> <tr> <td>One</td> <td>Two</td> <td>Three</td> </tr> <tr> <td>One</td> <td>Two</td> <td>Three</td> </tr> </table> </body> </html>