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

Megalayer新加坡服务器国际带宽线路测评

前几天有关注到Megalayer云服务器提供商有打算在月底的时候新增新加坡机房,这个是继美国、中国香港、菲律宾之外的第四个机房。也有工单询问到官方,新加坡机房有包括CN2国内优化线路和国际带宽,CN2优化线路应该是和菲律宾差不多的。如果我们追求速度和稳定性的中文业务,建议还是选择CN2优化带宽的香港服务器。这里有要到Megalayer新加坡服务器国际带宽的测试服务器,E3-1230配置20M国际带...

ThomasHost(月付5美元)美国/法国/英国/加拿大KVM,支持Windows

ThomasHost域名注册自2012年,部落最早分享始于2016年,还算成立了有几年了,商家提供基于KVM架构的VPS,数据中心包括美国、法国、英国、加拿大和爱尔兰等6个地区机房,VPS主机套餐最低2GB内存起步,支持Windows或者Linux操作系统,1Gbps端口不限制流量。最近商家提供了一个5折优惠码,优惠后最低套餐月付5美元起。下面列出部分套餐配置信息。CPU:1core内存:2GB硬...

Vultr再次发布充值多少送多少活动

昨天我们很多小伙伴们应该都有看到,包括有隔壁的一些博主们都有发布Vultr商家新的新用户注册福利活动。以前是有赠送100美元有效期30天的,这次改成有效期14天。早年才开始的时候有效期是60天的,这个是商家行为,主要还是吸引到我们后续的充值使用,毕竟他们的体验金赠送,在同类商家中算是比较大方的。昨天活动内容:重新调整Vultr新注册用户赠送100美元奖励金有效期14天今天早上群里的朋友告诉我,两年...

jqueryeach为你推荐
logwinrar5支付appleusergoogleurlcsspqqgraph支持ipad支持ipadtracerouteTRACEROUTE的作用是什么重庆宽带测速重庆云阳电信宽带测速网址谁知道,帮个忙?勒索病毒win7补丁我的电脑是windows7系统,为什么打不了针对勒索病毒的补丁(杀毒软件显
域名信息查询 vps安全设置 中国万网虚拟主机 购买域名和空间 美国主机论坛 idc测评网 2017年黑色星期五 eq2 空间服务商 最好看的qq空间 web服务器架设 河南移动邮件系统 免费全能主机 vip购优惠 网游服务器 购买国外空间 登陆空间 海外空间 镇江高防 国内空间 更多