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

阿里云服务器绑定域名的几个流程整理

今天遇到一个网友,他之前一直在用阿里云虚拟主机,我们知道虚拟主机绑定域名是直接在面板上绑定的。这里由于他的网站项目流量比较大,虚拟主机是不够的,而且我看他虚拟主机已经有升级过。这里要说的是,用过阿里云虚拟主机的朋友可能会比较一下价格,实际上虚拟主机价格比云服务器还贵。所以,基于成本和性能的考虑,建议他选择云服务器。毕竟他的备案都接入在阿里云。这里在选择阿里云服务器后,他就蒙圈不知道如何绑定域名。这...

无忧云:洛阳BGP云服务器低至38.4元/月起;雅安高防云服务器/高防物理机优惠

无忧云怎么样?无忧云,无忧云是一家成立于2017年的老牌商家旗下的服务器销售品牌,现由深圳市云上无忧网络科技有限公司运营,是正规持证IDC/ISP/IRCS商家,主要销售国内、中国香港、国外服务器产品,线路有腾讯云国外线路、自营香港CN2线路等,都是中国大陆直连线路,非常适合免备案建站业务需求和各种负载较高的项目,同时国内服务器也有多个BGP以及高防节点。一、无忧云官网点击此处进入无忧云官方网站二...

ZJI:香港物理服务器,2*E5-2630L/32G/480G SSD/30Mbps/2IP/香港BGP,月付520元

zji怎么样?zji是一家老牌国人主机商家,公司开办在香港,这个平台主要销售独立服务器业务,和hostkvm是同一样,两个平台销售的产品类别不一平,商家的技术非常不错,机器非常稳定。昨天收到商家的优惠推送,目前针对香港邦联四型推出了65折优惠BGP线路服务器,性价比非常不错,有需要香港独立服务器的朋友可以入手,非常适合做站。zji优惠码:月付/年付优惠码:zji 物理服务器/VDS/虚拟主机空间订...

jqueryeach为你推荐
TableBasicAbnormallyStoppedServicesitunes支持ipadcss3圆角css实现圆角的几种方法是什么?netbios端口如何组织netbios端口的外部通信勒索病毒win7补丁求问win7 64位旗舰版怎么预防勒索病毒iphone连不上wifi苹果iphone6/plus wifi连接不上怎么办ipad上网ipad上网速度很慢怎么回事?win7如何关闭445端口如何判断445端口是否关闭win7还原系统电脑怎么恢复出厂设置win7旗舰版杀毒软件免费下载2013排行榜杀毒软件排行榜2015有哪些?
域名买卖 国外域名 qq空间域名 technetcal 2014年感恩节 mediafire下载 seovip php探针 天互数据 双拼域名 789电视 绍兴电信 免费dns解析 申请免费空间和域名 江苏双线服务器 lamp是什么意思 lamp的音标 阵亡将士纪念日 umax asp空间 更多