一、 $(document).ready()&window.onload區別:
window.onload在網頁多有元素(包含元素的全部關聯文件)徹底加載到瀏覽器後才執行,即JS此時才能夠訪問網頁中的任何元素;
$(document).ready()在DOM徹底就緒時就能夠被調用,此時網頁的全部元素對jQuery而言都是能夠訪問的,但這時並不意味着這些元素關聯的文件都已經下載完畢。
window.onload事件一次只能保存對一個函數的引用,它會自動用後面的函數覆蓋前面的函數,所以不能在現有行爲上添加新的行爲;
$(document).ready()每次調用都會在現有的行爲上追加新的行爲,這些行爲函數會根據註冊的順序依次執行。html
二、 toggle()方法: toggle(fn1,fn2...fnN)
toggle()方法用於模擬鼠標連續單擊事件,第一次單擊元素,觸發指定的第一個函數fn1,依次類推,直到觸發最後一個。隨後的每次單擊都重複對這幾個函數的輪番調用;
toggle()在jQuery中還有另外一個做用:切換元素的可見狀態,以下: 瀏覽器
$("div").toggle(function(){
$(this).next().show();
},function(){
$(this).next().hide();
})app
三、事件冒泡ide
以下代碼:
函數
<script> $("span").bind("click",function(){ var txt = $("msg").html()+"<p>內層span元素被單擊</p>"; $("msg").html(txt); }) $("content").bind("click",function(){ var txt = $("msg").html()+"<p>外層div元素被單擊</p>"; $("msg").html(txt); }) $("body").bind("click",function(){ var txt = $("msg").html()+"<p>body元素被單擊</p>"; $("msg").html(txt); }) </script> <div id="content"> 外層div元素 <span>內層span元素</span> 外層div元素 </div> <div id="msg"></div>
事件會按照DOM得層次結構依次向上直至頂端,若是須要中止事件冒泡,stopPropagation()方法以下:
$("span").bind("click",function(event){
var txt = $("msg").html()+"<p>內層span元素被單擊</p>";
$("msg").html(txt);
event.stopPropagation();
})動畫
表單提交時若是須要阻止默認行爲(文本框輸入值爲空是不容許提交),須要使用preventDefault()方法:this
<script> $(function(){ $("#sub").bind("click",function(event)){ var username = $("username").val(); if(username == ""){ $("#msg").html("<p>文本框不能爲空</p>"); event.preventDefault(); } }) }) </script> <form> username:<input type="text" id="username"/> <input type="submit" value="commit" id="sub"/> </form> <div id="msg"></div>
若是想同時對事件對對象中止冒泡和默認行爲,可在事件處理中返回false,以下:
event.preventDefault() -------> return false;
enent.stopPorpagation() -------> return false;spa
四、其餘用法
1)綁定多個事件類型:
下面這兩種寫法是等同的:
$(function(){
$("#div").bind("mouseover mouseout",function()){
$(this).toggleClass("over");
})
})orm
$(function(){
$("#div").bind("mouseover",function()){
$(this).toggleClass("over");
}).bind("mouseout"),function(){
$(this).toggleClass("over");
})htm
2) 相同事件名稱,不一樣命名空間的執行方法
$(function(){
$("#div").bind("click",function()){
$("body").append("<p>click事件</p>");
});
$("#div").bind("click.plugin",function()){
$("body").append("<p>click.plugin事件</p>");
});
$("#button").bind("click",function()){
$("body").trigger("click!");
});
})
當點擊<div>元素後,會同時觸發click和click.plugin事件,若是隻是點擊<button>元素,則只觸發click事件,不觸發click.plugin事件,
(注意trigger("click!")中!的做用是匹配全部不包含在命名空間中的click方法)
五、jQuery動畫
1) 中止動畫:stop()方法
stop(): 只中止當前正在進行的動畫;
stop(true): 把當前元素接下來還沒有執行完的動畫隊列清空;
stop(true,true): 中止當前動畫並直接到達當前動畫的末狀態,並清空動畫隊列;
stop(false,true): 讓當前動畫直接到達末狀態
jQuery只能設置正在執行的動畫的最終狀態,而沒有提供直接到達未執行動畫隊列最終狀態的方法。
2)判斷元素是否處於動畫狀態if(! $(element).is(":animated")){ doSomeThing...}