body和document的梗
http://bbs.zhinengshe.com/thread-1199-1-1.html
1. 在空白的页面加点击事件,是加在body上么 ?
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script> 7 window.onload = function () { 8 document.body.onclick = function () { 9 alert("hello"); 10 } 11 } 12 </script> 13 </head> 14 <body> 15 </body> 16 </html>
2. document是什么 ?
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script> 7 window.onload = function () { 8 alert(document.childNodes[1].tagName); 9 } 10 </script> 11 </head> 12 <body> 13 </body> 14 </html>
弹出结果为"HTML". 代码中最顶层的节点为<!DOCTYPE html>和<html>,其实这两个节点有一个虚拟的父节点,这个父节点就是document.
3. 把点击事件加在document上,事情就靠谱了~
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script> 7 window.onload = function () { 8 document.onclick = function () { 9 alert("hello"); 10 } 11 } 12 </script> 13 </head> 14 <body> 15 </body> 16 </html>