學習jQuery必須知道常用的幾種方法

jQuery事件處理

ready(fn)

Js代碼

   1. $(document).ready(function(){ 

   2.   // Your code here... 

   3. }); 

$(document).ready(function(){

  // Your code here...

});

作用:它可以極大地提高web應用程序的響應速度。通過使用這個方法,可以在DOM載入就緒能夠讀取並操縱時立即調用你所綁定的函數,而99.99%的JavaScript函數都需要在那一刻執行。

bind(type,[data],fn)

Js代碼

   1. $("p").bind("click", function(){ 

   2.   alert( $(this).text() ); 

   3. });  

$("p").bind("click", function(){

  alert( $(this).text() );

});

作用:爲每一個匹配元素的特定事件(像click)綁定一個事件處理器函數。起到事件監聽的作用。

toggle(fn,fn)

Js代碼

   1. $("td").toggle( 

   2.   function () { 

   3.     $(this).addClass("selected"); 

   4.   }, 

   5.   function () { 

   6.     $(this).removeClass("selected"); 

   7.   } 

   8. ); 

$("td").toggle(

  function () {

    $(this).addClass("selected");

  },

  function () {

    $(this).removeClass("selected");

  }

);

作用:每次點擊時切換要調用的函數。如果點擊了一個匹配的元素,則觸發指定的第一個函數,當再次點擊同一元素時,則觸發指定的第二個函數。挺有趣的一個函數,在動態實現某些功能的時候可能會用到。(像click(),focus(),keydown()這樣的事件這裏就不提了,那些都是開發中比較常用到的。)

jQuery外觀效果

addClass(class)和removeClass(class)

Js代碼

   1. $(".stripe tr").mouseover(function(){   

   2.                $(this).addClass("over");}).mouseout(function(){  

   3.                $(this).removeClass("over");}) 

   4. }); 

$(".stripe tr").mouseover(function(){ 

               $(this).addClass("over");}).mouseout(function(){

               $(this).removeClass("over");})

});

 也可以寫成:

Js代碼

   1. $(".stripe tr").mouseover(function() { $(this).addClass("over") }); 

   2. $(".stripe tr").mouseout(function() { $(this).removeClass("over") }); 

$(".stripe tr").mouseover(function() { $(this).addClass("over") });

$(".stripe tr").mouseout(function() { $(this).removeClass("over") });

作用:爲指定的元素添加或移除樣式,從而實現動態的樣式效果,上面的實例中實現鼠標移動雙色表格的代碼

css(name,value)

$("p").css("color","red");

作用:很簡單,就是在匹配的元素中,設置一個樣式屬性的值。這個個人感覺和上面的addClass(class)有點類似。

slide(),hide(),fadeIn(), fadeout(), slideUp() ,slideDown()

$("#btnShow").bind("click",function(event){ $("#divMsg").show() });

$("#btnHide").bind("click",function(evnet){ $("#divMsg").hide() });

作用:jQuery中提供的比較常用的幾個動態效果的函數。還可以添加參數:show(speed,[callback])以優雅的動畫顯示所有匹配的元素,並在顯示完成後可選地觸發一個回調函數。

原文鏈接:http://www.javaeye.com/topic/871265

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章