smallerjqueryeach

jqueryeach  时间:2021-05-17  阅读:()
APPENDIX279DOMScriptingLibrariesThroughoutthebookyou'vefocusedonlearningthebasicsoftheDOM.
YouusedthestandardsetofDOMmethodstoperformcommontasksandlearnedhowbesttoapplythosemethodsinyourscripts.
Youmayhavenoticedthatsometimesyourcodewasalittleverboseandrepetitive.
RestrictingyourselftoonlyDOMmethodssuchasdocument.
getElementByIdcangettiring,especiallywhenlibrariesprovidealmostmagicalfunctionslike$thatdoevenmore.
Librariesarepackagesofreusablecodethatofferanumberofadvantages.
Theircodehasbeentestedandprovenbyalargeuserbase.
Theycaneasilyfitintoyourexistingdevelopmentframeworks.
Theyprovidequick,elegantsolutionsformostofyourmundaneday-to-dayDOMscriptingtasks,reducingmultiplelinesofcodedowntoasinglefunction.
Theyprovidecross-browsersolutionssoyoudon'thavetoworryabouteverydifferentbrowser.
Librariesfreeyoutoworkonthegoodstuffinyourapplications,vastlyincreasingyourproductivity.
Theyarewonderful,butusingalibraryisnotthebandageforeveryproblem.
Librariesarecreatedbyothers,notyou.
Thatmeansyoumightnotunderstandwhat'sgoingoninsideanddealingwithbugsorproblemsmaybemoredifficult.
Tousealibrary,youneedtoincludethatlibraryalongwithyourscripts.
Thisaddsanotherrequesttoyourpageloadandmayuseupvaluablebandwidth.
Mixingandmatchinglibrariescanleadtoconflictsoralotofredundantfeatures.
Librariescanalsobecomeacrutchifyouneverventurebeyondthem.
Beforedivingin,besuretotakethetimetoactuallylearnbothJavaScriptandtheDOMasyouhaveinthisbook.
SinceChapter1,I'veemphasizedthenecessityoflearninghowthingsworkandnotsimplywhattheydo.
Therearemanywonderfullibrariesoutthere,someofwhichI'llpointouthere,buthavingnounderstandingofwhat'sgoingonbehindthesceneswillbedetrimentaltobothyouandyourwebapplication.
Withoutthatdeeperunderstanding,you'llbelostinthesmalldetailsthatalibraryoftenassumesyoualreadyknow.
Justtobeclear,I'mnotpersonallyaffiliatedwithanyoftheselibraries,soIhavenopersonalbiastowardsoneortheother.
I'malsonotsayingtheselibrariesareultimatelythebestforeverysituationnoraretheytheonlyonesavailable.
Theseexamplessimplyprovidesomeofthecleanestalternativesolutionsfortasksyou'vealreadyworkedthroughinthebook.
We'regoingtorevisitsomeofthetopicsyou'vealreadyseen,includingthese:SyntaxSelectingelementsAPPENDIXDOMSCRIPTINGLIBRARIES280ManipulatingtheDOMdocumentHandlingeventsAnimationAjaxYou'llseehowlibrariescanhandlethesetasks—oftenwithmuchlesscodeforyou—leavingmoretimetofocusonbusinesslogicinsteadofrepetitiveboringscripting.
NoteEachlibrarycanaccomplishprettymucheverytaskinonewayoranother,soI'llpointoutoneortwomethodsthatIconsiderthebestormostusefulforeacharea—Iwon'tbecoveringeveryaspectofeachlibrary,sobesuretocheckthedocumentationforeachtofindoutwhatelseisavailable.
Beforeyoubegintoworkwithlibraries,it'simportanttochoosetherightone.
Let'slookatafewthingsthatmighthelpyoudecide.
ChoosingalibraryWhenyoudecideit'stimetoinvestigatealibrary,thebiggestproblemischoosingamongthehundredsthatareavailable.
Thereareseveralcriteriayoushouldconsiderinyourdecision:Doesithaveallthefeaturesyou'relookingforMixingandmatchinglibrariescanbeproblematic.
Commonmethodssuchas$()orget()oftenusethesamesyntaxbuthandlethingsdifferently.
Additionally,ifyouusemorethanonelibraryatthesametime,you'llusuallyendupwithalotofduplicatedfeaturesandredundantcode.
DoesithavemorefeaturesthanyouneedHavingtoofewfeaturesisoneproblem,butabulkylibrarywithwaytoomanyisalsoaproblem.
Whenalibraryhasmorefeaturesthanyouneed,oryou'renottakingadvantageofthemall,youmaywanttoconsideralighterversionthatwon'ttakeaslongtodownload.
Thisisespeciallyimportantinmobileenvironments.
IsitmodularLibrarieswithabundantfeaturesoftenworkaroundfilesizebymodularizingfeaturesintodifferentfiles.
Thisletsyouminimizefilesizebyloadingonlythefilesandfeaturesyouneed.
Mostofthetime,you'llhavetobesuretoincludeallthenecessaryfiles,butafewlibrariesmayofferadynamicloadingmechanismwhereyouonlyneedtoincludeonefileandthatfilewillfetchothersasnecessary.
Justbecarefulaboutthenumberofrequestsyouanticipate.
Oftenonelargerequestisbetterthanseveralsmallerones.
IsitwellsupportedLackofanactivedevelopercommunitymeansnobugfixesorfeatureimprovements.
Also,havingmanyeyeslookingatandsharingthesamelibrarymeansfewerbugsandmorereliableresults.
Agoodcommunitybehindthelibrarybringsnotonlyfixesandfeaturesbutalsoalotofsupportwhenyourunintoaproblemandneedmorehelp.
APPENDIXDOMSCRIPTINGLIBRARIES281DoesithavedocumentationWithoutdocumentation,you'llbelost.
Sure,youmightcomeacrosssomeexamplethatothershavehackedtogether,butalackofofficialdocumentationusuallyindicatesalackofenthusiasmbydevelopersandthusaprojectthatmaybegoingnowhere.
DoesithavetherightlicenseJustbecauseyoucanviewthesourceonlinedoesn'tmeanit'sfreeforthetaking.
Beforeusingalibrary,verifythatitslicensecoverswhatyouintendedtodowithitandthatyou'vemetanyspecialrequirements.
Onceyou'vechosenanappropriatelibraryandyou'reproducinggreatthings,don'tforgettotrytocontributebacktothecommunity!
Theselibrariesareallbuiltbydedicateddeveloperswhoareoftenworkingwithwhatlittlesparetimetheyhavetoimprovethetoolsyouusedaily.
Ifyoucan'thelpwithdevelopmenteffortsorbugtesting,youcouldalwaysprovideexamplesandtutorialsorsimplyhelpbuildthedocumentation—anyeffortishelpfulandwillmakethelibraryevenbetter.
AfewlibrariesForthisAppendixI'veselectedafewexamplesbasedontheprecedingcriteriaaswellasgeneralpopularityandabitofpersonalpreference.
MostexamplesusejQuerybutthereareseveralotherlibrarieswithsimilarfeatures.
Eachhasitsownprosandconsasoutlinedhere.
jQuery(http://jquery.
com)describesitselfas"afastandconciseJavaScriptLibrarythatsimplifiesHTMLdocumenttraversing,eventhandling,animating,andAjaxinteractionsforrapidwebdevelopment.
jQueryisdesignedtochangethewaythatyouwriteJavaScript.
"jQuery'sextremelypowerfulselectionmethod,chainingsyntax,andsimplifiedAjaxandeventmethodswillmakeyourcodecompactandeasytofollow.
ThereisalsoaverylargecommunitybehindjQuerywithanumberofdifferentplug-indeveloperswho'veaddedfeaturesbeyondthelibrarybasics.
Prototype(http://prototypejs.
org)describesitselfas"aJavaScriptFrameworkthataimstoeasedevelopmentofdynamicwebapplications.
"PrototypehasanumberofgreatDOM-manipulationfunctionsaswellasoneofthemorepopularAjaxobjects.
ItwasoneofthefirstpopularJavaScriptlibrariesandwasthelibrarythatoriginatedthe$()selectorfunction.
TheYahoo!
UserInterface(YUI)Library(http://developer.
yahoo.
com/yui)describesitselfas"asetofutilitiesandcontrols,writteninJavaScript,forbuildingrichlyinteractivewebapplicationsusingtechniquessuchasDOMscripting,DHTML,andAJAX.
TheYUILibraryalsoincludesseveralcoreCSSresources.
"YUIhasagreatdevelopercommunityandtonsofdocumentation.
ThelibrariesarefilledwitheveryfeatureyoucanthinkoffromsimpleDOMmanipulationtoadvancedeffectsandfullyfeaturedwidgets.
Asawhole,thelibraryisnicelydividedintosmallfilesandnamespacesbutitsometimesbecomesoverwhelmingtryingtodeterminewhatyouneedandwheretofindit—youknowit'sbigwhenjustthecheatsheetisover20pages.
DojoToolkit(http://www.
dojotoolkit.
org/)saysthatit"savesyoutime,deliverspowerfulperformance,andscaleswithyourdevelopmentprocess.
It'sthetoolkitexperienceddevelopersturntoforbuildinggreatwebexperiences.
"Dojoisafull-featuredJavaScripttoolkitusedbyanumberoflargecompanies.
Ithasalargedevelopercommunity,gooddocumentation,andseveralbooksdevotedtoit.
APPENDIXDOMSCRIPTINGLIBRARIES282MooTools(http://mootools.
net/)describesitselfas"acompact,modular,Object-OrientedJavaScriptframeworkdesignedfortheintermediatetoadvancedJavaScriptdeveloper.
Itallowsyoutowritepowerful,flexible,andcross-browsercodewithitselegant,welldocumented,andcoherentAPI.
"MooToolsisextensivelydocumentedandhasalargeusercommunity.
ItnotonlyincludesanumberofgreatDOMenhancementsbutalsointegratestheMoo.
fxeffectslibraryforsimpleandcomplexanimations.
NoteSomelibraries,suchasPrototypeandjQuery,sharethesame$()functionsyntax.
Ifyoudecidetousealibraryinyourproductionenvironment,besuretoreadthedocumentationforyourchosenlibrarytoseehowitmaydifferfromwhatI'mpresentinghereorhowitmayconflictwithotherlibraries.
ContentdeliverynetworksWheneverpossibleyouwanttoreducetheoverallsizeofyourdocumentsandallowthebrowsertocachefilesasmuchaspossible.
Inaddition,youwanttoservethosefilesupasfastaspossible.
Inthecaseoflibraries,ifanumberofdifferentsitesusethesamelibrary,itwouldmakesensetohostthatlibraryinacommonlocationthatallsitescouldaccessandshare.
Thisway,ifusersgofromsitetositetheydon'tneedtodownloadthesamefileoverandoveragain.
Acontentdeliverynetwork(CDN)solvestheproblemofsharedlibrarydistribution.
TheCDNisanetworkofserverswhosesoleresponsibilityisdeliveringcommoncontent.
Theseserverseachcontaincopiesofthelibraryandareplacedatvariousgeographicallocationstomaximizebandwidthandspeed.
BrowserswillaccessalibraryatacommonURLwhiletheunderlyingstructureoftheCDNallowstheclosestandspeediestservertoservethefile,avoidingbottlenecksintheoverallsystem.
GoogleprovidesafreeCDNforanumberoflibraries,includingDojojQueryMooToolsPrototypeYahoo!
UserInterfaceLibrary(YUI)Forafulllistofthemostrecentversionsandthespecificdetailsofeachlibrary,seehttp://code.
google.
com/apis/libraries/devguide.
html.
TouseaCDN,yousimplyincludethelibrarylikeanyotherJavaScriptfile.
Forexample,asofthiswritingthemostrecentGoogleCDNjQueryURLishttps://ajax.
googleapis.
com/ajax/libs/jquery/1.
4.
3/jquery.
min.
js,soyoucanaddthefollowingtoyourdocuments:Ifyou'rehesitanttorelysolelyonGoogleoranotherserviceasyourdistributionnetwork,it'sagoodideatoprovideafailsafefallbacktoalocalfileonyourserverincasetheCDNbecomesunavailable.
Youcansimplychecktoseeiftheappropriateobjectsareloadedandthenincludealocallibraryifnecessary:APPENDIXDOMSCRIPTINGLIBRARIES283!
window.
jQuery&&document.
write(unescape('%3Cscriptsrc="scripts/jquery-1.
4.
3.
min.
js"%3E%3C/script%3E'))NoteThismethodusesdocument.
writetoaddatagtothedocumentifthejQuerylibrarydidn'tcreatetheglobalwindow.
jQueryobject.
The$functionusedelsewhereintheAppendixistheshortformfortheproperjQueryobjectname.
Withthiscodeinplace,iftheservergoesdownitwon'ttakeyoursitewithit.
SyntaxBeforepresentingsomeexamplesIshouldpointoutafewsyntaxoptionsthatmanylibrariesrelyon.
NoteAnumberoflibraries,suchasjQuery,Prototype,MooToolsandothers,offerthedollarsign$()functionasashortcuttotheirselectormethod.
IusethisthroughouttheAppendixsothatthecodeismoregeneric.
Justrememberthatthoughthesyntaxofthefunctioncallsmayappearsimilar,theunderlyingobjectstheycreatearedrasticallydifferent.
Makesureyoureadthedocumentationforyourselectedlibrarytoseehowits$functionworks.
Mostlibrariesoffertheabilityto"chain"methodstogetherusingdotnotation—aperiodjoinsthemethodcalls—similartothewayyou'vealreadyseenwhenusingmethodssuchasgetElemenById:document.
getElementById('example').
nodeName;ThisisafundamentalaspectoflibrariessuchasjQuery,inwhichmethodsarecreatedspecificallytoallowyoutowritecomplicatedscriptsinveryshortchains.
It'snotuncommontoseeone-linescriptsthatdoalotofwork.
Forexample,toremoveandthenaddaclassnametoeveryparagraphinadocumentusingjQuery,youcandothis:$('p').
removeClass('classFoo').
addClass('classBar');That'salotcleanerthantheaddclassfunctionyoucreatedinChapter9.
We'llgetmoreintothat$('p')selectorinamoment.
OneadditionalthingIwillmentionisiteration.
Librariesofferloopingstructuresformanipulatinglistsofelements,andthechainingsyntaxoftenprovidesaverycleanwayofdoingthis.
Forexample,usingjQueryagain,youcanreplicatethisloopfromChapter3:varitems=document.
getElementsByTagName("li");for(vari=0;itagB')selectsalltagBelementsthataredirectchilddescendantsoftagAelements.
$('tagA+tagB')selectsalltagBsiblingelementsthatimmediatelyfollowtagAelements.
$('tagA~tagB')selectsallelementswithaprecedingsiblingtagBelement.
Also,youcanuseseveralpseudo-classandpseudo-elementselectorsincludingthese:$('tag:root')selectsthetagelementthatistherootofthedocument.
$('tag:nth-child(n)')selectsalltagelementsthatarethenthchildrenoftheirparents,countingfromthefirstone.
$('tag:nth-last-child(n)')selectsalltagelementsthatarethenthchildoftheirparents,countingfromthelastone.
$('tag:nth-of-type(n)')selectsalltagelementsthatarethenthsiblingoftheirtype,countingfromthefirstone.
$('tag:nth-last-of-type(n)')selectsalltagelementsthatarethenthsiblingoftheirtype,countingfromthelastone.
$('tag:first-child')selectsanytagelementthatisthefirstchildofitsparents.
$('tag:last-child')selectsanytagelementthatisthelastchildofitsparent.
APPENDIXDOMSCRIPTINGLIBRARIES286$('tag:first-of-type')selectsanytagelementthatisthefirstsiblingofitstype.
$('tag:last-of-type')selectsanytagelementthatisthelastsiblingofitstype.
$('tag:only-child')selectsanytagelementthatisanonlychildofitsparent.
$('tag:only-of-type')selectsanytagelementthatistheonlysiblingofitstype.
$('tag:empty')selectsalltagelementsthathavenochildren.
$('tag:enabled')selectsalluserinterfacetagelementsthatareenabled.
$('tag:disabled')selectsalluserinterfacetagelementsthataredisabled.
$('tag:checked')selectsalluserinterfacetagelementsthatarechecked,suchascheckboxesandradiobuttons.
$('tag:not(s)')selectsalltagelementsthatdon'tmatchtheselectors.
Differentlibrarieshavevaryingsupportforeachselectortype,socheckthedocumentationforyourchosenlibrary.
Withtheseselectors,youcanquicklyaccessveryspecificelementsinyourdocumentsbasedontheirpositionratherthanclassorID.
Thiswillhelpyoukeepyourmarkupfreeofscript-specificIDsandclassesaswellasreduceyourelementselectioncode.
Forexample,youcantakethiscodethatusesDOMmethodstoselectallthelinkswithinnavelementswithinarticles:varlinks=[];vararticles=document.
getElementsByTagName("article");for(vara=0;aNoImagesHereTwohere!
UsingtheYUIYAHOO.
util.
Dom.
getElementBymethod,youcansimplyusetheexistingDOMelementpropertiesyou'veseenearlierinthebooktofilteryourlist:varsingleImageAnchors=YAHOO.
util.
Dom.
getElementsBy(function(e){//Lookfornodeswithonechildimagereturn(e.
nodeName=='A'&&e.
getElementsByTagName('img').
length==1);});APPENDIXDOMSCRIPTINGLIBRARIES289ThesingleImageAnchorsvariablewillcontainalistwithareferenceto,asit'stheonlyanchorwithoneimageasachildintheexamplelist.
PrototypeandjQueryprovidefindAllandfiltermethods,respectively.
Youusetheselasttwointhechainingcontexttofilteroutelementsreturnedfromtheexpression.
First,here'showitlooksinPrototype(usingthe$$selectorfunction)://PrototypelibrarycallbackfiltervarsingleImageAnchors=$$('a').
findAll(function(e){return(e.
descendants().
findAll(function(e){return(e.
nodeName=='IMG');}).
length==1);});Here'sthesamemethodinjQuery://jQuerylibrarycallbackfiltervarsingleImageAnchors=$('a').
filter(function(){return($('img',this).
length==1)});InmostcasesthePrototypeandjQueryexpressionselectorsshouldbeenoughtofilterthelistofelements,butincaseswhereyouneedmorein-depthanalysisoftheelements,callbackscanbeverypowerful.
ManipulatingtheDOMdocumentLibrariesarechock-fullofdifferentDOM-manipulationmethods,asthat'sprettymuchthepointofthelibraryinthefirstplace.
I'lljustpointoutafewandletyouexplorethedocumentationforeachlibrarytofindtherest.
CreatingcontentUsingjQuerytocreatenewDOMelementsisveryeasy.
YoucandefineHTMLastheinputtothe$functiontocreatenodes.
Forexampleherewe'llappendanewdivtothebodyofadocument.
ThedivwillhaveanidofexampleandthecontentofHello:$('Hello

云雀云(larkyun)低至368元/月,广州移动1Gbps带宽VDS(带100G防御),常州联通1Gbps带宽VDS

云雀云(larkyun)当前主要运作国内线路的机器,最大提供1Gbps服务器,有云服务器(VDS)、也有独立服务器,对接国内、国外的效果都是相当靠谱的。此外,还有台湾hinet线路的动态云服务器和静态云服务器。当前,larkyun对广州移动二期正在搞优惠促销!官方网站:https://larkyun.top付款方式:支付宝、微信、USDT广移二期开售8折折扣码:56NZVE0YZN (试用于常州联...

Hostinger 限时外贸美国主机活动 低至月12元且赠送1个COM域名

Hostinger 商家我们可能一些新用户不是太熟悉,因为我们很多新人用户都可能较多的直接从云服务器、独立服务器起步的。而Hostinger商家已经有将近十年的历史的商家,曾经主做低价虚拟主机,也是比较有知名度的,那时候也有接触过,不过一直没有过多的使用。这不这么多年过去,Hostinger商家一直比较稳妥的在运营,最近看到这个商家在改版UI后且产品上也在活动策划比较多。目前Hostinger在进...

3C云1核1G 9.9元 4核4G 16元 美国Cera 2核4G 24元

3C云互联怎么样?3C云互联专注免备案香港美国日本韩国台湾云主机vps服务器,美国高防CN2GIA,香港CN2GIA,顶级线路优化,高端品质售后无忧!致力于对互联网云计算科技深入研发与运营的极客共同搭建而成,将云计算与网络核心技术转化为最稳定,安全,高速以及极具性价比的云服务器等产品提供给用户!专注为个人开发者用户,中小型,大型企业用户提供一站式核心网络云端服务部署,促使用户云端部署化简为零,轻松...

jqueryeach为你推荐
人文社科winrar上海工程技术大学桥面163支持ipadeacceleratoraccess violation问题的解决办法!ipad连不上wifiipad显示无互联网连接怎么回事?win10关闭445端口在win10 如何关闭445端口的最新相关信息iphone连不上wifi苹果手机“无法加入网络”怎么办win7telnetwindows7的TELNET服务在哪里开启啊win7如何关闭445端口如何关闭WIN7自动配置 IPV4 地址 169.254
备案域名购买 广州主机租用 阿里云邮箱登陆首页 mach 优惠码 流媒体服务器 php主机 香港机房托管 天猫双十一秒杀 智能骨干网 e蜗 165邮箱 qq对话框 酷番云 空间首页登陆 shuang12 下载速度测试 web应用服务器 iki 徐州电信 更多