JavaScript Dom0 Dom1
行为 样式 结构相分离的页面
JS CSS HTML
DOM 0写法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table border="1" width="300px"> <tr onmousemove="t1(0);" onmouseout="t2(0)"><td>1</td><td>2</td><td>3</td></tr> <tr onmousemove="t1(1);" onmouseout="t2(1)"><td>1</td><td>2</td><td>3</td></tr> <tr onmousemove="t1(2);" onmouseout="t2(2)"><td>1</td><td>2</td><td>3</td></tr> </table> <script> //DOM 0实现的效果 function t1(n){ var mytrs = document.getElementsByTagName('tr')[n]; console.log(mytrs); mytrs.style.backgroundColor = "red"; } function t2(n){ var mytrs = document.getElementsByTagName('tr')[n]; console.log(mytrs); mytrs.style.backgroundColor = ""; } </script> </body> </html> Demo
DOM 1写法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <style> .c1{ background-color: cadetblue; width: 300px; } </style> <body> <div class="c1"> <table border="1" width="300px"> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> </table> </div> <script> //DOM 1实现的效果 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 = ""; } } </script> </body> </html>
第一种非常低效,每次都要在标签上绑定。
第二种相对高效一点,首先获取DOM对象,然后一次绑定。