dom0:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table border="1" width="300px"> <tr onmouseover="t1(0);" onmouseout="t2(0);"><td>1</td><td>2</td><td>3</td></tr> <tr onmouseover="t1(1);" onmouseout="t2(1);"><td>1</td><td>2</td><td>3</td></tr> <tr onmouseover="t1(2);" onmouseout="t2(2);"><td>1</td><td>2</td><td>3</td></tr> </table> <script> function t1(n) { var myTrs = document.getElementsByTagName("tr")[n]; myTrs.style.backgroundColor="red"; } function t2(n) { var myTrs = document.getElementsByTagName("tr")[n]; myTrs.style.backgroundColor=""; } </script> </body> </html>
dom1:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table border="1" width="300px"> <tr onmouseover="t1(0);" onmouseout="t2(0);"><td>1</td><td>2</td><td>3</td></tr> <tr onmouseover="t1(1);" onmouseout="t2(1);"><td>1</td><td>2</td><td>3</td></tr> <tr onmouseover="t1(2);" onmouseout="t2(2);"><td>1</td><td>2</td><td>3</td></tr> </table> <script> var myTrs = document.getElementsByTagName("tr"); var len = myTrs.length; for (var i=0;i<len;i++){ myTrs[i].onmouseover = function () { this.style.backgroundColor="red"; // 谁调用这个函数this就指向谁 }; myTrs[i].onmouseout = function () { this.style.backgroundColor=""; // 谁调用这个函数this就指向谁 }; } </script> </body> </html>