7个为开发者准备的有用的jQuery技巧
一、在新窗口打开链接
用下面的代码,你点击链接即可在新窗口打开:
$(document).ready(function(){
//selectallanchortagsthathavehttpinthehref
//andapplythetarget=_blank
$("a[href^='http']").attr('target','_blank');
});
二、设置等高的列
应用下面的代码,可以使得你的WEB应用每一列高度都想等:
<divclass="equalHeight"style="border:1pxsolid">
<p>FirstLine</p>
<p>SecondLine</p>
<p>ThirdLine</p>
</div>
<divclass="equalHeight"style="border:1pxsolid">
<p>ColumnTwo</p>
</div>
<scriptsrc="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
equalHeight('.equalHeight');
});
//globalvariable,thiswillstorethehighestheightvalue
varmaxHeight=0;
functionequalHeight(col){
//Getalltheelementwithclass=col
col=$(col);
//Loopallthecol
col.each(function(){
//Storethehighestvalue
if($(this).height()>maxHeight){
maxHeight=$(this).height();
}
});
//Settheheight
col.height(maxHeight);
}
</script>
三、jQuery预加载图像
这个小技巧可以提升页面加载图片的速度:
jQuery.preloadImagesInWebPage=function(){
for(varctr=0;ctr<arguments.length;ctr++){
jQuery("").attr("src",arguments[ctr]);
}
}
//使用方法:
$.preloadImages("image1.gif","image2.gif","image3.gif");
//检查图片是否被加载
$('#imageObject').attr('src','image1.gif').load(function(){
alert('Theimagehasbeenloaded…');
});
四、禁用鼠标右键
$(document).ready(function(){
//catchtheright-clickcontextmenu
$(document).bind("contextmenu",function(e){
//warningprompt-optional
alert("Noright-clicking!");
//deletethedefaultcontextmenu
returnfalse;
});
});
五、设定计时器
$(document).ready(function(){
window.setTimeout(function(){
//somecode
},500);
});
六、计算子元素的个数
<divid="foo">
<divid="bar"></div>
<divid="baz">
<divid="biz"></div>
<span><span></span></span>
</div>
</div>
<scriptsrc="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<scripttype="text/javascript">
//jQuerycodetocountchildelements$("#foo>div").size()
alert($("#foo>div").size())
</script>
七、把元素定位到页面中间
<divid="foo"style="width:200px;height:200px;background:#ccc;"></div>
<scriptsrc="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<scripttype="text/javascript">
jQuery.fn.center=function(){
this.css("position","absolute");
this.css("top",($(window).height()-this.height())/2+$(window).scrollTop()+"px");
this.css("left",($(window).width()-this.width())/2+$(window).scrollLeft()+"px");
returnthis;
}
//Usetheabovefunctionas:
$('#foo').center();
</script>