当前位置:编程学习 > JAVA >>

简单jQuery使用技巧

1.使用最新的jquery版本

觉得这个建议有待商榷,虽然越新的jquery版本性能上更加优秀,但是有些方法的变迁还是会导致一些bug,比如从1.4.2到1.5时很多朋友就抱怨ajax上出现问题了。建议是旧的页面的jquery升级需谨慎,新项目可以大胆的使用jquery新版本。
还有个建议是使用google的cdn上的jquery文件,加载速度更快。猛击Google Libraries API 进入查看。

 2.保持选择器的简单

这个建议明河非常赞同,有很多朋友不喜欢给元素增加样式或id,希望保持html的简洁,使用jquery强大的选择器去检索元素,这不是好的习惯。首先越复杂的选择器,遍历的效率越低,这是显而易见的,最高效率无疑是使用原生的getElementById();其次,复杂的选择器将标签名称和层级结构固化在里面,假如你的html结构发生了改变,或标签发生了改变,都直接造成检索失败。


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

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

访问DOM,是javascript最耗资源和性能的部分,所以尽量避免复杂或重复的遍历DOM。
避免重复遍历DOM的方法就是将$()检索的元素存储到变量,比如下面的代码:
[javascript]
var buttons = $('#navigation a.button'); 

var buttons = $('#navigation a.button');

// 使用$前缀来标示jquery对象,是非常好的习惯,推荐使用。
[javascript] 
var $buttons = $('#navigation a.button'); 

var $buttons = $('#navigation a.button');

jquery选择器支持大部分的css3伪类方法,像:visible, :hidden, :animated,虽然很便利,但请慎用,因为当你使用伪类选择器的时候,jQuery不得不使用querySelectorAll(),性能的损耗更大。


3.jQuery对象作为数组处理

jQuery对象定义了length属性,当使用数组的形式操作时候返回其实是DOM元素而不是子jQuery对象,比如下面代码。


[javascript] ttons:  
var buttons = $('#navigation a.button'); 

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


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

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


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

var firstFour = buttons.slice(0,4);

根据实验,使用for或while循环,执行效率比$.each()来的高。详细测试可以看several times faster。
使用length属性来检查元素存在性:
[javascript] 
if(buttons){ // This is always true  
// Do something  

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

if(buttons){ // This is always true
// Do something
}

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

 


4.selector属性

jQuery对象都带有一个selector属性,用于获取选择器名称,比如:


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

$('#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对象时会用到。


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

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

 


6.选择随机元素

应用场景不多,举个例子,现在你需要随机给li增加一个red的class。


[javascript] 
 

需要扩展jquery的选择器,这段代码很好的演示了jQuery.expr的用法。

[javascript] 
(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'); 

(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属性。


[javascript] 
$.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); 

$.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是用的非常多的函数,可以实现不少华丽的效果。当内置的缓动效果无法满足你的需求时,还可以自定义缓动函数。


[javascript]
$.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'); 

$.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()

补充:web前端 , JavaScript ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,