jQuery中的100个技巧汇总
1.当document文档就绪时执行JavaScript代码。
我们为什么使用jQuery库呢?原因之一就在于我们可以使jQuery代码在各种不同的浏览器和存在bug的浏览器上完美运行。
<scriptsrc="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
//DifferentwaystoachievetheDocumentReadyevent
//WithjQuery
$(document).ready(function(){/*...*/});
//ShortjQuery
$(function(){/*...*/});
//WithoutjQuery(doesn'tworkinolderIEversions)
document.addEventListener('DOMContentLoaded',function(){
//Yourcodegoeshere
});
//TheTrickshot(workseverywhere):
r(function(){
alert('DOMReady!');
})
functionr(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
</script>
2.使用route。
<scriptsrc="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
varroute={
_routes:{},//Therouteswillbestoredhere
add:function(url,action){
this._routes[url]=action;
},
run:function(){
jQuery.each(this._routes,function(pattern){
if(location.href.match(pattern)){
//"this"pointstothefunctiontobeexecuted
this();
}
});
}
}
//Willexecuteonlyonthispage:
route.add('002.html',function(){
alert('Hellothere!')
});
route.add('products.html',function(){
alert("thiswon'tbeexecuted:(")
});
//Youcanevenuseregex-es:
route.add('.*.html',function(){
alert('Thisisusingaregex!')
});
route.run();
</script>
3.使用JavaScript中的AND技巧。
使用&&操作符的特点是如果操作符左边的表达式是false,那么它就不会再判断操作符右边的表达式了。所以:
//Insteadofwritingthis:
if($('#elem').length){
//dosomething
}
//Youcanwritethis:
$('#elem').length&&log("doingsomething");
4.is()方法比你想象的更为强大。
下面举几个例子,我们先写一个id为elem的div。js代码如下:
//First,cachetheelementintoavariable:
varelem=$('#elem');
//Isthisadiv?
elem.is('div')&&log("it'sadiv");
//Doesithavethebigboxclass?
elem.is('.bigbox')&&log("ithasthebigboxclass!");
//Isitvisible?(wearehidingitinthisexample)
elem.is(':not(:visible)')&&log("itishidden!");
//Animating
elem.animate({'width':200},1);
//isitanimated?
elem.is(':animated')&&log("itisanimated!");
其中判断是否为动画我觉得非常不错。
5.判断你的网页一共有多少元素。
通过使用$("*").length();方法可以判断网页的元素数量。
//Howmanyelementsdoesyourpagehave?
log('Thispagehas'+$('*').length+'elements!');
6.使用length()属性很笨重,下面我们使用exist()方法。
/Oldway
log($('#elem').length==1?"exists!":"doesn'texist!");
//Trickshot:
jQuery.fn.exists=function(){returnthis.length>0;}
log($('#elem').exists()?"exists!":"doesn'texist!");
7.jQuery方法$()实际上是拥有两个参数的,你知道第二个参数的作用吗?
//Selectanelement.Thesecondargumentiscontexttolimitthesearch
//Youcanuseaselector,jQueryobjectordomelement
$('li','#firstList').each(function(){
log($(this).html());
});
log('-----');
//Createanelement.Thesecondargumentisan
//objectwithjQuerymethodstobecalled
vardiv=$('<div>',{
"class":"bigBlue",
"css":{
"background-color":"purple"
},
"width":20,
"height":20,
"animate":{//YoucanuseanyjQuerymethodasaproperty!
"width":200,
"height":50
}
});
div.appendTo('#result');
8.使用jQuery我们可以判断一个链接是否是外部的,并来添加一个icon在非外部链接中,且确定打开方式。
这里用到了hostname属性。
<ulid="links">
<li><ahref="007.html">Theprevioustip</a></li>
<li><ahref="./009.html">Thenexttip</a></li>
<li><ahref="http://www.google.com/">Google</a></li>
</ul>
//Loopthroughallthelinks
$('#linksa').each(function(){
if(this.hostname!=location.hostname){
//Thelinkisexternal
$(this).append('<imgsrc="assets/img/external.png"/>')
.attr('target','_blank');
}
});
9.jQuery中的end()方法可以使你的jQuery链更加高效。
<ulid="meals"><li><ulclass="breakfast"><liclass="eggs">No</li><liclass="toast">No</li><liclass="juice">No</li></ul></li></ul>
//Hereishowitisused:
varbreakfast=$('#meals.breakfast');
breakfast.find('.eggs').text('Yes')
.end()//backtobreakfast
.find('.toast').text('Yes')
.end()
.find('.juice').toggleClass('juicecoffee').text('Yes');
breakfast.find('li').each(function(){
log(this.className+':'+this.textContent)
});
10.也许你希望你的web应用感觉更像原生的,那么你可以阻止contextmenu默认事件。
<script>
//Preventrightclickingonthispage
$(function(){
$(document).on("contextmenu",function(e){
e.preventDefault();
});
});
</script>
11.一些站点可能会使你的网页在一个bar下面,即我们所看到在下面的网页是iframe标签中的,我们可以这样解决。
//Hereishowitisused:
if(window!=window.top){
window.top.location=window.location;
}
else{
alert('Thispageisnotdisplayedinaframe.Open011.htmltoseeitinaction.');
}
12.你的内联样式表并不是被设置为不可改变的,如下:
//Makethestylesheetvisibleandeditable
$('#regular-style-block').css({'display':'block','white-space':'pre'})
.attr('contentEditable',true);
这样即可改变内联样式了。
13.有时候我们不希望网页的某一部分内容被选择比如复制粘贴这种事情,我们可以这么做:
<pclass="descr">Incertainsituationsyoumightwanttopreventtextonthepagefrombeingselectable.Tryselectingthistextandhitviewsourcetoseehowitisdone.</p>
<script>
//Preventtextfrombeingselected
$(function(){
$('p.descr').attr('unselectable','on')
.css('user-select','none')
.on('selectstart',false);
});
</script>
这样,内容就不能被选择啦。
14.从CDN中引入jQuery,这样的方法可以提高我们网站的性能,并且引入最新的版本也是一个不错的主意。
下面会介绍四种不同的方法。
<!--Case1-requestingjQueryfromtheofficialCDN--> <scriptsrc="http://code.jquery.com/jquery-1.10.2.min.js"></script> <!--Case2-requestingjQueryfromGoogle'sCDN(noticetheprotocol)--> <!--<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>--> <!--Case3-requestingthelatestminor1.8.xversion(onlycachedforanhour)--> <!--<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.10/jquery.min.js"></script>--> <!--Case4-requestingtheabsolutelatestjQueryversion(usewithcaution)--> <!--<scriptsrc="http://code.jquery.com/jquery.min.js"></script>-->
15.保证最小的DOM操作。
我们知道js操作DOM是非常浪费资源的,我们可以看看下面的例子。
CODE
//Bad
//varelem=$('#elem');
//for(vari=0;i<100;i++){
//elem.append('<li>element'+i+'</li>');
//}
//Good
varelem=$('#elem'),
arr=[];
for(vari=0;i<100;i++){
arr.push('<li>element'+i+'</li>');
}
elem.append(arr.join(''));
16.更方便的分解URL。
也许你会使用正则表达式来解析URL,但这绝对不是一种好的方法,我们可以借用a标签来实现它。
//Youwanttoparsethisaddressintoparts:
varurl='http://tutorialzine.com/books/jquery-trickshots?trick=12#comments';
//Thetrickshot:
vara=$('<a>',{href:url});
log('Hostname:'+a.prop('hostname'));
log('Path:'+a.prop('pathname'));
log('Query:'+a.prop('search'));
log('Protocol:'+a.prop('protocol'));
log('Hash:'+a.prop('hash'));
17.不要害怕使用vanilla.js。
jQuery背负的太多,这便是原因,你可以用一般的js。
//PrinttheIDsofallLIitems
$('#colorsli').each(function(){
//AccesstheIDdirectly,instead
//ofusingjQuery's$(this).attr('id')
log(this.id);
});
18.最优化你的选择器
//Let'strysomebenchmarks!
variterations=10000,i;
timer('Fancy');
for(i=0;i<iterations;i++){
//ThisfallsbacktoaSLOWJavaScriptdomtraversal
$('#peanutButterdiv:first');
}
timer_result('Fancy');
timer('Parent-child');
for(i=0;i<iterations;i++){
//Better,butstillslow
$('#peanutButterdiv');
}
timer_result('Parent-child');
timer('Parent-childbyclass');
for(i=0;i<iterations;i++){
//Somebrowsersareabitfasteronthisone
$('#peanutButter.jellyTime')
19.缓存你的selector。
//Bad:
//$('#pancakesli').eq(0).remove();
//$('#pancakesli').eq(1).remove();
//$('#pancakesli').eq(2).remove();
//Good:
varpancakes=$('#pancakesli');
pancakes.eq(0).remove();
pancakes.eq(1).remove();
pancakes.eq(2).remove();
//Alternatively:
//pancakes.eq(0).remove().end()
//.eq(1).remove().end()
//.eq(2).remove().end();
20.对于重复的函数只定义一次
如果你追求代码的更高性能,那么当你设置事件监听程序时必须小心,只定义一次函数然后把它的名字作为事件处理程序传递是不错的方法。
$(document).ready(function(){
functionshowMenu(){
alert('Showingmenu!');
//Doingsomethingcomplexhere
}
$('#menuButton').click(showMenu);
$('#menuLink').click(showMenu);
});
21.像对待数组一样地对待jQuery对象
由于jQuery对象有index值和长度,所以这意味着我们可以把对象当作普通的数组对待。这样也会有更好地性能。
vararr=$('li'),
iterations=100000;
timer('NativeLoop');
for(varz=0;z<iterations;z++){
varlength=arr.length;
for(vari=0;i<length;i++){
arr[i];
}
}
timer_result('NativeLoop');
timer('jQueryEach');
for(z=0;z<iterations;z++){
arr.each(function(i,val){
this;
});
}
timer_result('jQueryEach');
未完待续...
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!