jQuery使用技巧簡單匯總
更新時(shí)間:2013年04月18日 15:16:01 作者:
本文將詳細(xì)介紹下jQuery對象作為數(shù)組處理、創(chuàng)建一個(gè)空的jQuery對象、selector屬性、選擇隨機(jī)元素,感興趣的朋友可以參考下哈
1.使用最新的jquery版本
覺得這個(gè)建議有待商榷,雖然越新的jquery版本性能上更加優(yōu)秀,但是有些方法的變遷還是會導(dǎo)致一些bug,比如從1.4.2到1.5時(shí)很多朋友就抱怨ajax上出現(xiàn)問題了。建議是舊的頁面的jquery升級需謹(jǐn)慎,新項(xiàng)目可以大膽的使用jquery新版本。
還有個(gè)建議是使用google的cdn上的jquery文件,加載速度更快。猛擊Google Libraries API 進(jìn)入查看。
<!-- 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.保持選擇器的簡單
這個(gè)建議明河非常贊同,有很多朋友不喜歡給元素增加樣式或id,希望保持html的簡潔,使用jquery強(qiáng)大的選擇器去檢索元素,這不是好的習(xí)慣。首先越復(fù)雜的選擇器,遍歷的效率越低,這是顯而易見的,最高效率無疑是使用原生的getElementById();其次,復(fù)雜的選擇器將標(biāo)簽名稱和層級結(jié)構(gòu)固化在里面,假如你的html結(jié)構(gòu)發(fā)生了改變,或標(biāo)簽發(fā)生了改變,都直接造成檢索失敗。
$('li[data-selected="true"] a') // Fancy, but slow
$('li.selected a') // Better
$('#elem') // Best
訪問DOM,是javascript最耗資源和性能的部分,所以盡量避免復(fù)雜或重復(fù)的遍歷DOM。
避免重復(fù)遍歷DOM的方法就是將$()檢索的元素存儲到變量,比如下面的代碼:
var buttons = $('#navigation a.button');
// 使用$前綴來標(biāo)示jquery對象,是非常好的習(xí)慣,推薦使用。
var $buttons = $('#navigation a.button');
var $buttons = $('#navigation a.button');
jquery選擇器支持大部分的css3偽類方法,像:visible, :hidden, :animated,雖然很便利,但請慎用,因?yàn)楫?dāng)你使用偽類選擇器的時(shí)候,jQuery不得不使用querySelectorAll(),性能的損耗更大。
3.jQuery對象作為數(shù)組處理
jQuery對象定義了length屬性,當(dāng)使用數(shù)組的形式操作時(shí)候返回其實(shí)是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);
根據(jù)實(shí)驗(yàn),使用for或while循環(huán),執(zhí)行效率比$.each()來的高。詳細(xì)測試可以看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對象都帶有一個(gè)selector屬性,用于獲取選擇器名稱,比如:
$('#container li:first-child').selector // #container li:first-child
$('#container li').filter(':first-child').selector // #container li.filter(:first-child)
留意第二行代碼,selector返回的是獲取的元素完整的選擇器。
這個(gè)屬性常用于編寫jquery插件的時(shí)候。
5.創(chuàng)建一個(gè)空的jQuery對象
這種情況應(yīng)用場景不多,當(dāng)你需要先創(chuàng)建個(gè)空的jQuery對象,然后使用add()方法向此對象注入jQuery對象時(shí)會用到。
var container = $([]);
container.add(another_element);)
6.選擇隨機(jī)元素
應(yīng)用場景不多,舉個(gè)例子,現(xiàn)在你需要隨機(jī)給li增加一個(gè)red的class。
需要擴(kuò)展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;
};
10.
11.})(jQuery);
12.
13.
14.
15.$('li:random').addClass('glow');
7.使用css鉤子
jQuery.cssHooks是1.4.3新增的方法,用的不估計(jì)不多,當(dāng)你定義新的CSS Hooks時(shí)實(shí)際上定義的是getter和setter方法,舉個(gè)例子,border-radius這個(gè)圓角屬性想要成功應(yīng)用于firefox、webkit等瀏覽器,需要增加屬性前綴,比如-moz-border-radius和-webkit-border-radius。你可以通過定義CSS Hooks將其封裝成統(tǒng)一的接口borderRadius,而不是一一設(shè)置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
}
};
10.
11.// Use it without worrying which property the browser actually understands:
12.$('#rect').css('borderRadius',5);
8.使用自定義的Easing(緩動動畫效果)函數(shù)
easing plugin是用的非常多的函數(shù),可以實(shí)現(xiàn)不少華麗的效果。當(dāng)內(nèi)置的緩動效果無法滿足你的需求時(shí),還可以自定義緩動函數(shù)。
$.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()的使用
關(guān)于$.proxy(),明河曾經(jīng)詳細(xì)介紹過,傳送門在此《jquery1.4教程三:新增方法教程(3)》。
jquery有個(gè)讓人頭疼的地方,回調(diào)函數(shù)過多,上下文this總是在變化著,有時(shí)候我們需要控制this的指向,這時(shí)候就需要$.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();
});
10.});
嵌套的二個(gè)回調(diào)函數(shù)this指向是不同的!現(xiàn)在我們希望this的指向是#panel的元素。代碼如下:
$('#panel').fadeIn(function(){
// Using $.proxy to bind this:
$('#panel button').click($.proxy(function(){
// this points to #panel
$(this).fadeOut();
},this));
});
10.快速獲取節(jié)點(diǎn)數(shù)
這是個(gè)常用的技巧,代碼如下:
console.log( $('*').length );
11.構(gòu)建個(gè)jquery插件
(function($){
$.fn.yourPluginName = function(){
// Your code goes here
return this;
};
})(jQuery);
關(guān)于jquery插件的構(gòu)建,明河曾發(fā)過系列教程,傳送門:制作jquery文字提示插件—jquery插件實(shí)戰(zhàn)教程(1)。
這里就不再詳述。
12.設(shè)置ajax全局事件
關(guān)于ajax全局事件,明河曾發(fā)過完整的介紹文章,傳送門:《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});
當(dāng)存在多個(gè)animate動畫時(shí),如何處理動畫的執(zhí)行順序是個(gè)煩心事,原文作者是建議使用delay()函數(shù),如上面的代碼,但明河的建議是使用queue()方法,因?yàn)閐elay你要考慮延遲多少時(shí)間,而queue沒有這個(gè)問題,進(jìn)入隊(duì)列的函數(shù)會一個(gè)個(gè)順序執(zhí)行??梢钥疵骱右郧暗奈恼聁ueue和dequeue—明河談jquery。
15.jquery的本地存儲
本地存儲在現(xiàn)在web應(yīng)用中使用越來越頻繁,jquery有個(gè)專門用于本地存儲的插件叫$.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);
}
覺得這個(gè)建議有待商榷,雖然越新的jquery版本性能上更加優(yōu)秀,但是有些方法的變遷還是會導(dǎo)致一些bug,比如從1.4.2到1.5時(shí)很多朋友就抱怨ajax上出現(xiàn)問題了。建議是舊的頁面的jquery升級需謹(jǐn)慎,新項(xiàng)目可以大膽的使用jquery新版本。
還有個(gè)建議是使用google的cdn上的jquery文件,加載速度更快。猛擊Google Libraries API 進(jìn)入查看。
復(fù)制代碼 代碼如下:
<!-- 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.保持選擇器的簡單
這個(gè)建議明河非常贊同,有很多朋友不喜歡給元素增加樣式或id,希望保持html的簡潔,使用jquery強(qiáng)大的選擇器去檢索元素,這不是好的習(xí)慣。首先越復(fù)雜的選擇器,遍歷的效率越低,這是顯而易見的,最高效率無疑是使用原生的getElementById();其次,復(fù)雜的選擇器將標(biāo)簽名稱和層級結(jié)構(gòu)固化在里面,假如你的html結(jié)構(gòu)發(fā)生了改變,或標(biāo)簽發(fā)生了改變,都直接造成檢索失敗。
復(fù)制代碼 代碼如下:
$('li[data-selected="true"] a') // Fancy, but slow
$('li.selected a') // Better
$('#elem') // Best
訪問DOM,是javascript最耗資源和性能的部分,所以盡量避免復(fù)雜或重復(fù)的遍歷DOM。
避免重復(fù)遍歷DOM的方法就是將$()檢索的元素存儲到變量,比如下面的代碼:
復(fù)制代碼 代碼如下:
var buttons = $('#navigation a.button');
// 使用$前綴來標(biāo)示jquery對象,是非常好的習(xí)慣,推薦使用。
復(fù)制代碼 代碼如下:
var $buttons = $('#navigation a.button');
var $buttons = $('#navigation a.button');
jquery選擇器支持大部分的css3偽類方法,像:visible, :hidden, :animated,雖然很便利,但請慎用,因?yàn)楫?dāng)你使用偽類選擇器的時(shí)候,jQuery不得不使用querySelectorAll(),性能的損耗更大。
3.jQuery對象作為數(shù)組處理
jQuery對象定義了length屬性,當(dāng)使用數(shù)組的形式操作時(shí)候返回其實(shí)是DOM元素而不是子jQuery對象,比如下面代碼。
復(fù)制代碼 代碼如下:
// Selecting all the navigation buttons:
var buttons = $('#navigation a.button');
// 遍歷buttons對象
復(fù)制代碼 代碼如下:
for(var i=0;i<buttons.length;i++){
console.log(buttons[i]); // 是DOM元素,而不是jQuery對象!
}
// We can even slice it:
復(fù)制代碼 代碼如下:
var firstFour = buttons.slice(0,4);
根據(jù)實(shí)驗(yàn),使用for或while循環(huán),執(zhí)行效率比$.each()來的高。詳細(xì)測試可以看several times faster。
使用length屬性來檢查元素存在性:
復(fù)制代碼 代碼如下:
if(buttons){ // This is always true
// Do something
}
if(buttons.length){ // True only if buttons contains elements
// Do something
}
4.selector屬性
jQuery對象都帶有一個(gè)selector屬性,用于獲取選擇器名稱,比如:
復(fù)制代碼 代碼如下:
$('#container li:first-child').selector // #container li:first-child
$('#container li').filter(':first-child').selector // #container li.filter(:first-child)
留意第二行代碼,selector返回的是獲取的元素完整的選擇器。
這個(gè)屬性常用于編寫jquery插件的時(shí)候。
5.創(chuàng)建一個(gè)空的jQuery對象
這種情況應(yīng)用場景不多,當(dāng)你需要先創(chuàng)建個(gè)空的jQuery對象,然后使用add()方法向此對象注入jQuery對象時(shí)會用到。
復(fù)制代碼 代碼如下:
var container = $([]);
container.add(another_element);)
6.選擇隨機(jī)元素
應(yīng)用場景不多,舉個(gè)例子,現(xiàn)在你需要隨機(jī)給li增加一個(gè)red的class。
需要擴(kuò)展jquery的選擇器,這段代碼很好的演示了jQuery.expr的用法。
復(fù)制代碼 代碼如下:
(function($){
var random = 0;
$.expr[':'].random = function(a, i, m, r) {
if (i == 0) {
random = Math.floor(Math.random() * r.length);
}
return i == random;
};
10.
11.})(jQuery);
12.
13.
14.
15.$('li:random').addClass('glow');
7.使用css鉤子
jQuery.cssHooks是1.4.3新增的方法,用的不估計(jì)不多,當(dāng)你定義新的CSS Hooks時(shí)實(shí)際上定義的是getter和setter方法,舉個(gè)例子,border-radius這個(gè)圓角屬性想要成功應(yīng)用于firefox、webkit等瀏覽器,需要增加屬性前綴,比如-moz-border-radius和-webkit-border-radius。你可以通過定義CSS Hooks將其封裝成統(tǒng)一的接口borderRadius,而不是一一設(shè)置css屬性。
復(fù)制代碼 代碼如下:
$.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
}
};
10.
11.// Use it without worrying which property the browser actually understands:
12.$('#rect').css('borderRadius',5);
8.使用自定義的Easing(緩動動畫效果)函數(shù)
easing plugin是用的非常多的函數(shù),可以實(shí)現(xiàn)不少華麗的效果。當(dāng)內(nèi)置的緩動效果無法滿足你的需求時(shí),還可以自定義緩動函數(shù)。
復(fù)制代碼 代碼如下:
$.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()的使用
關(guān)于$.proxy(),明河曾經(jīng)詳細(xì)介紹過,傳送門在此《jquery1.4教程三:新增方法教程(3)》。
jquery有個(gè)讓人頭疼的地方,回調(diào)函數(shù)過多,上下文this總是在變化著,有時(shí)候我們需要控制this的指向,這時(shí)候就需要$.proxy()方法。
復(fù)制代碼 代碼如下:
<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();
});
10.});
嵌套的二個(gè)回調(diào)函數(shù)this指向是不同的!現(xiàn)在我們希望this的指向是#panel的元素。代碼如下:
復(fù)制代碼 代碼如下:
$('#panel').fadeIn(function(){
// Using $.proxy to bind this:
$('#panel button').click($.proxy(function(){
// this points to #panel
$(this).fadeOut();
},this));
});
10.快速獲取節(jié)點(diǎn)數(shù)
這是個(gè)常用的技巧,代碼如下:
復(fù)制代碼 代碼如下:
console.log( $('*').length );
11.構(gòu)建個(gè)jquery插件
復(fù)制代碼 代碼如下:
(function($){
$.fn.yourPluginName = function(){
// Your code goes here
return this;
};
})(jQuery);
關(guān)于jquery插件的構(gòu)建,明河曾發(fā)過系列教程,傳送門:制作jquery文字提示插件—jquery插件實(shí)戰(zhàn)教程(1)。
這里就不再詳述。
12.設(shè)置ajax全局事件
關(guān)于ajax全局事件,明河曾發(fā)過完整的介紹文章,傳送門:《jquery的ajax全局事件詳解—明河談jquery》。
13.延遲動畫
復(fù)制代碼 代碼如下:
// 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});
當(dāng)存在多個(gè)animate動畫時(shí),如何處理動畫的執(zhí)行順序是個(gè)煩心事,原文作者是建議使用delay()函數(shù),如上面的代碼,但明河的建議是使用queue()方法,因?yàn)閐elay你要考慮延遲多少時(shí)間,而queue沒有這個(gè)問題,進(jìn)入隊(duì)列的函數(shù)會一個(gè)個(gè)順序執(zhí)行??梢钥疵骱右郧暗奈恼聁ueue和dequeue—明河談jquery。
15.jquery的本地存儲
本地存儲在現(xiàn)在web應(yīng)用中使用越來越頻繁,jquery有個(gè)專門用于本地存儲的插件叫$.jStorage jQuery plugin。
復(fù)制代碼 代碼如下:
// 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);
}
相關(guān)文章
jquery與google map api結(jié)合使用 控件,監(jiān)聽器
關(guān)于jquery的獲取不再此處累贅,網(wǎng)上有許多關(guān)于jquery的介紹。2010-03-03
jquery插件之定時(shí)查詢待處理任務(wù)數(shù)量
這篇文章主要介紹了jquery定時(shí)查詢待處理任務(wù)數(shù)量插件示例2014-05-05
JQuery通過后臺獲取數(shù)據(jù)遍歷到前臺的方法
今天小編就為大家分享一篇JQuery通過后臺獲取數(shù)據(jù)遍歷到前臺的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
jquery實(shí)現(xiàn)焦點(diǎn)輪播效果
本文主要介紹了jquery實(shí)現(xiàn)焦點(diǎn)輪播效果的示例代碼,具有很好的參考價(jià)值,下面跟著小編一起來看下吧2017-02-02
jQuery中attr()與prop()函數(shù)用法實(shí)例詳解(附用法區(qū)別)
這篇文章主要介紹了jQuery中attr()與prop()函數(shù)用法,結(jié)合實(shí)例形式詳細(xì)分析了attr()與prop()函數(shù)的使用技巧與相關(guān)注意事項(xiàng),并附帶了attr()與prop()函數(shù)用法的區(qū)別,需要的朋友可以參考下2015-12-12

