簡單jQuery使用技巧

1.使用最新的jquery版本

覺得這個建議有待商榷,雖然越新的jquery版本性能上更加優秀,但是有些方法的變遷還是會導致一些bug,比如從1.4.2到1.5時很多朋友就抱怨ajax上出現問題了。建議是舊的頁面的jquery升級需謹慎,新項目可以大膽的使用jquery新版本。
還有個建議是使用google的cdn上的jquery文件,加載速度更快。猛擊Google Libraries API 進入查看。

<!-- Include a specific version of jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<!-- Include the latest version in the 1.6 branch -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>


2.保持選擇器的簡單

這個建議明河非常贊同,有很多朋友不喜歡給元素增加樣式或id,希望保持html的簡潔,使用jquery強大的選擇器去檢索元素,這不是好的習慣。首先越複雜的選擇器,遍歷的效率越低,這是顯而易見的,最高效率無疑是使用原生的getElementById();其次,複雜的選擇器將標籤名稱和層級結構固化在裏面,假如你的html結構發生了改變,或標籤發生了改變,都直接造成檢索失敗。

$('li[data-selected="true"] a') // Fancy, but slow
$('li.selected a') // Better
$('#elem') // Best


訪問DOM,是javascript最耗資源和性能的部分,所以儘量避免複雜或重複的遍歷DOM。
避免重複遍歷DOM的方法就是將$()檢索的元素存儲到變量,比如下面的代碼:
var buttons = $('#navigation a.button');


// 使用$前綴來標示jquery對象,是非常好的習慣,推薦使用。
var $buttons = $('#navigation a.button');


jquery選擇器支持大部分的css3僞類方法,像:visible, :hidden, :animated,雖然很便利,但請慎用,因爲當你使用僞類選擇器的時候,jQuery不得不使用querySelectorAll(),性能的損耗更大。


3.jQuery對象作爲數組處理

jQuery對象定義了length屬性,當使用數組的形式操作時候返回其實是DOM元素而不是子jQuery對象,比如下面代碼。

// Selecting all the navigation buttons:
var buttons = $('#navigation a.button');



// 遍歷buttons對象
for(var i=0;i<buttons.length;i++){
console.log(buttons[i]); // 是DOM元素,而不是jQuery對象!
}



// We can even slice it:
var firstFour = buttons.slice(0,4);


根據實驗,使用for或while循環,執行效率比$.each()來的高。詳細測試可以看several times faster。
使用length屬性來檢查元素存在性:
if(buttons){ // This is always true
// Do something
}

if(buttons.length){ // True only if buttons contains elements
// Do something
}



4.selector屬性

jQuery對象都帶有一個selector屬性,用於獲取選擇器名稱,比如:

$('#container li:first-child').selector // #container li:first-child
$('#container li').filter(':first-child').selector // #container li.filter(:first-child)


留意第二行代碼,selector返回的是獲取的元素完整的選擇器。
這個屬性常用於編寫jquery插件的時候。


5.創建一個空的jQuery對象

這種情況應用場景不多,當你需要先創建個空的jQuery對象,然後使用add()方法向此對象注入jQuery對象時會用到。

var container = $([]);
container.add(another_element);)



6.選擇隨機元素

應用場景不多,舉個例子,現在你需要隨機給li增加一個red的class。

需要擴展jquery的選擇器,這段代碼很好的演示了jQuery.expr的用法。

(function($){
var random = 0;

$.expr[':'].random = function(a, i, m, r) {
if (i == 0) {
random = Math.floor(Math.random() * r.length);
}
return i == random;
};

})(jQuery);



$('li:random').addClass('glow');


7.使用css鉤子

jQuery.cssHooks是1.4.3新增的方法,用的不估計不多,當你定義新的CSS Hooks時實際上定義的是getter和setter方法,舉個例子,border-radius這個圓角屬性想要成功應用於firefox、webkit等瀏覽器,需要增加屬性前綴,比如-moz-border-radius和-webkit-border-radius。你可以通過定義CSS Hooks將其封裝成統一的接口borderRadius,而不是一一設置css屬性。

$.cssHooks['borderRadius'] = {
        get: function(elem, computed, extra){
            // Depending on the browser, read the value of
// -moz-border-radius, -webkit-border-radius or border-radius
        },
        set: function(elem, value){
            // Set the appropriate CSS3 property
        }
};

// Use it without worrying which property the browser actually understands:
$('#rect').css('borderRadius',5);



8.使用自定義的Easing(緩動動畫效果)函數

easing plugin是用的非常多的函數,可以實現不少華麗的效果。當內置的緩動效果無法滿足你的需求時,還可以自定義緩動函數。

$.easing.easeInOutQuad = function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
};

// To use it:
$('#elem').animate({width:200},'slow','easeInOutQuad');



9.$.proxy()的使用

關於$.proxy(),明河曾經詳細介紹過,傳送門在此《jquery1.4教程三:新增方法教程(3)》。
jquery有個讓人頭疼的地方,回調函數過多,上下文this總是在變化着,有時候我們需要控制this的指向,這時候就需要$.proxy()方法。

<div id="panel" style="display:none">
<button>Close</button>
</div>
$('#panel').fadeIn(function(){
// this points to #panel
$('#panel button').click(function(){
// this points to the button
$(this).fadeOut();
});
});


嵌套的二個回調函數this指向是不同的!現在我們希望this的指向是#panel的元素。代碼如下:
$('#panel').fadeIn(function(){
// Using $.proxy to bind this:

$('#panel button').click($.proxy(function(){
// this points to #panel
$(this).fadeOut();
},this));
});



10.快速獲取節點數

這是個常用的技巧,代碼如下:

console.log( $('*').length );



11.構建個jquery插件

(function($){
$.fn.yourPluginName = function(){
// Your code goes here
return this;
};
})(jQuery);


關於jquery插件的構建,明河曾發過系列教程,傳送門:製作jquery文字提示插件—jquery插件實戰教程(1)。
這裏就不再詳述。


12.設置ajax全局事件

關於ajax全局事件,明河曾發過完整的介紹文章,傳送門:《jquery的ajax全局事件詳解—明河談jquery》。


13.延遲動畫

// This is wrong:
$('#elem').animate({width:200},function(){
setTimeout(function(){
$('#elem').animate({marginTop:100});
},2000);
});

// Do it like this:
$('#elem').animate({width:200}).delay(2000).animate({marginTop:100});


當存在多個animate動畫時,如何處理動畫的執行順序是個煩心事,原文作者是建議使用delay()函數,如上面的代碼,但明河的建議是使用queue()方法,因爲delay你要考慮延遲多少時間,而queue沒有這個問題,進入隊列的函數會一個個順序執行。可以看明河以前的文章queue和dequeue—明河談jquery。


15.jquery的本地存儲

本地存儲在現在web應用中使用越來越頻繁,jquery有個專門用於本地存儲的插件叫$.jStorage jQuery plugin。

// Check if "key" exists in the storage
var value = $.jStorage.get("key");
if(!value){
// if not - load the data from the server
value = load_data_from_server();
// and save it
$.jStorage.set("key",value);
}


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