1.今天寫js碰到一個奇怪的問題,寫好的js放到body里面執行,但是放到head中沒有任何效果,為什么導致這種原因呢?
看失效代碼:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> new document </title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <style type="text/css"> .login{width:40px;height:25px;line-height:25px;background-color:#4E74A5;margin-top:30px;text-align:center;color:#FFF;} </style> <script type="text/javascript" src="jquery-1.7.1.min.js"></script> <script type="text/javascript"> $(".login").click(function(){ alert(1); }); </script> </head> <body> <input type="text" class="pass" /> <div id="enter" class="login"> 登錄</div> </body></html>2.解決辦法:把js代碼放到body中,或者利用 window.onload = function(){} 代碼包裹,文檔加載之后再執行,以后不建議放到head中。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> new document </title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <style type="text/css"> .login{width:40px;height:25px;line-height:25px;background-color:#4E74A5;margin-top:30px;text-align:center;color:#FFF;} </style> <script type="text/javascript" src="jquery-1.7.1.min.js"></script> <script type="text/javascript"> window.onload = function(){ $(".login").click(function(){ alert(1); }); } </script> </head> <body> <input type="text" class="pass" /> <div id="enter" class="login"> 登錄</div> </body></html>3.原因:
因為文檔還沒加載,就讀了js,js就不起作用了想在head里用的話,用window.onload = function(){//這里包裹你的代碼}
js可以分為外部的和內部的,外部的js一般放到head內。內部的js也叫本頁面的JS腳本,內部的js一般放到body內,這樣做的目的有很多:
1.不阻塞頁面的加載(事實上js會被緩存)。
2.可以直接在js里操作dom,這時候dom是準備好的,即保證js運行時dom是存在的。
3.建議的方式是放在頁面底部,監聽window.onload 或 readystate 來觸發js。
4.延伸:
head內的js會阻塞頁面的傳輸和頁面的渲染。head 內的 JavaScript 需要執行結束才開始渲染 body,所以盡量不要將 JS 文件放在 head 內。可以選擇在 document 完成時,或者特定區塊后引入和執行 JavaScript。head 內的 JavaScript 需要執行結束才開始渲染 body,所以盡量不要將 JS 文件放在 head 內。可以選擇在 document 完成時,或者特定區塊后引入和執行 JavaScript。
新聞熱點
疑難解答
圖片精選