jQuery实用技巧必备(下)
本文实例总结了经典且实用的jQuery代码开发技巧。分享给大家供大家参考。具体如下:
23.jQuery延时加载功能
Wanttodelaysomething?
$(document).ready(function(){ window.setTimeout(function(){ //dosomething },1000); });
24.移除单词功能
Wanttoremoveacertainword(s)?
$(document).ready(function(){ varel=$('#id'); el.html(el.html().replace(/word/ig,"")); });
25.验证元素是否存在于jquery对象集合中
Simplytestwiththe.lengthpropertyiftheelementexists.
$(document).ready(function(){ if($('#id').length){ //dosomething } });
26.使整个DIV可点击
Wanttomakethecompletedivclickable?
$(document).ready(function(){ $("div").click(function(){ //gettheurlfromhrefattributeandlaunchtheurl window.location=$(this).find("a").attr("href");returnfalse; }); //howtouse <DIV><Ahref="index.html">home</A></DIV> });
27.ID与Class之间转换
当改变Window大小时,在ID与Class之间切换
$(document).ready(function(){ functioncheckWindowSize(){ if($(window).width()>1200){ $('body').addClass('large'); } else{ $('body').removeClass('large'); } } $(window).resize(checkWindowSize); });
28.克隆对象
Cloneadivoranotherelement.
$(document).ready(function(){ varcloned=$('#id').clone(); //howtouse <DIVid=id></DIV> });
29.使元素居屏幕中间位置
Centeranelementinthecenterofyourscreen.
$(document).ready(function(){ 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; } $("#id").center(); });
30.写自己的选择器
Writeyourownselectors.
$(document).ready(function(){ $.extend($.expr[':'],{ moreThen1000px:function(a){ return$(a).width()>1000; } }); $('.box:moreThen1000px').click(function(){ //creatingasimplejsalertbox alert('Theelementthatyouhaveclickedisover1000pixelswide'); }); });
31.统计元素个数
Countanelement.
$(document).ready(function(){ $("p").size(); });
32.使用自己的Bullets
Wanttouseyourownbulletsinsteadofusingthestandardorimagesbullets?
$(document).ready(function(){ $("ul").addClass("Replaced"); $("ul>li").prepend("‒"); //howtouse ul.Replaced{list-style:none;} });
33.引用Google主机上的Jquery类库
LetGooglehostthejQueryscriptforyou.Thiscanbedonein2ways.
//Example1 <SCRIPTsrc="http://www.google.com/jsapi"></SCRIPT> <SCRIPTtype=text/javascript> google.load("jquery","1.2.6"); google.setOnLoadCallback(function(){ //dosomething }); </SCRIPT><SCRIPTtype=text/javascriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT> //Example2:(thebestandfastestway) <SCRIPTtype=text/javascriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT>
34.禁用Jquery(动画)效果
DisablealljQueryeffects
$(document).ready(function(){ jQuery.fx.off=true; });
35.与其他Javascript类库冲突解决方案
Toavoidconflictotherlibrariesonyourwebsite,youcanusethisjQueryMethod,andassignadifferentvariablenameinsteadofthedollarsign.
$(document).ready(function(){ var$jq=jQuery.noConflict(); $jq('#id').show(); });
以上就是所有关于jQuery实用技巧的全部内容,希望对大家的学习有所帮助。