【JQuery】jQuery(document).ready(function($) { });的幾種表示方法及load和ready的區別

來源:互聯網
上載者:User

標籤:優先順序   show   fine   net   ima   三種方式   處理   事件   cdn   

jQuery中處理載入時機的幾種方式

第一種:

jQuery(document).ready(function() {alert("你好");
});
//或$(document).ready(function() {alert("你好");});

第二種:

 jQuery(function() {alert("你好");});//或$(function() {alert("你好");});

第三種:

 (function() {alert("你好");})(jQuery);或(function() {alert("你好");})($);或(function() {    alert("你哈");})();

以上三種方式,第三種方式的執行優先順序比第一種、第二種都要高。第一種和第二種平級。

以上三種又可以用 window.onload = function () {};代替。

 

$(function(){})和window.onload(){}區別?

1.window.onload(){};需要等頁面所有的內容(包括元素的所有關聯檔案)都載入完成才會執行onload的代碼;

   $(function(){});在頁面的dom元素載入完畢後就執行,而無需等到圖片或其他媒體下載完畢;

執行下面這段代碼進行驗證:

 

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>區別驗證</title><script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script><script type="text/javascript">function img_load(){    alert($("img").attr("width"));//250}$(function(){    alert($("img").attr("width"));//undefined    $("img").attr("width","250px");});</script></head><body onload="img_load()"><img alt="" src="images/404.jpg" /></body></html>
$(function(){})和window.onload(){}區別驗證

 

2.$(document).ready()方法可以多次使用而註冊不同的事件處理常式,而window.onload一次只能儲存對一個函數的引用,多次綁定函數只會覆蓋前面的函數。

body.onload和window.onload(){}區別?

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>onload測試</title><script type="text/javascript">function test1(){    alert("我是test1");//顯示}function test2(){    alert("我是test2");//顯示}</script></head><body onload="test1(),test2()"></body></html>
onload載入多個函數測試

用$(window).load()載入多個函數

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script><script type="text/javascript">//window對象只能儲存一個函數的應用window.onload=function(){    alert("我是載入一");};window.onload=function(){    alert("我是載入二");//顯示};//使用下面的方法解決window載入多個函數$(window).load(function (){    alert("測試1");//顯示});$(window).load(function(){    alert("測試2");//顯示});</script></head><body></body></html>
window.load載入多個函數測試

 

原文連結:jQuery(document).ready(function($) { });的幾種表示方法

 

【JQuery】jQuery(document).ready(function($) { });的幾種表示方法及load和ready的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.