版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)
文檔簡介
11本科畢業(yè)設(shè)計外文文獻及譯文文獻、資料題目:JqueryInAction—UsingthejQueryflags文獻、資料來源:著作 文獻、資料發(fā)表(出版)日期:2008.7.15—院(部): 專 也 班 級 姓 在 學(xué) 號J 指導(dǎo)教庵 翻譯日期: 外文文獻:DOMwithjQueryutilityfunctions—UsingthejQueryflagsUsingthejQueryflagsSomeoftheinformationjQuerymakesavailabletousaspageauthors,andevenpluginauthors,isavailablenotviamethodsorfunctionsbutaspropertiesdefinedon$.Manyoftheseflagsarefocusedonhelpingusdivinethecapabilitiesofthecurrentbrowser,butothershelpuscontrolthebehaviorofjQueryatagloballevel.ThejQueryflagsintendedforpublicuseareasfollows:$.fx.off—Enablesordisabledeffects$.support—Detailssupportedfeatures$.browser—Exposesbrowserdetails(officiallydeprecated)Let’sstartbylookingathowjQueryletsusdisableanimations.DisablinganimationsTheremaybetimeswhenwemightwanttoconditionallydisableanimationsinapagethatincludesvariousanimatedeffects.Wemightdosobecausewe’vedetectedthattheplatformordeviceisunlikelytodealwiththemwell,orperhapsforaccessibilityreasons.Inanycase,wedon’tneedtoresorttowritingtwopages,onewithandonewithoutanimations.Whenwedetectwe’reinananimation-adverseenvironment,wecansimplysetthevalueof$.fx.offtotrue.Thiswillnotsuppressanyeffectswe’veusedonthepage;itwillsimplydisabletheanimationofthoseeffects.Forexample,thefadeeffectswillshowandhidetheelementsimmediately,withouttheinterveninganimations.Similarly,callstotheanimate()methodwillsettheCSSpropertiestothespecifiedfinalvalueswithoutanimatingthem.UsingthejQueryflagsOnepossibleuse-caseforthisflagmightbeforcertainmobiledevicesorbrowsersthatdon’tcorrectlysupportanimations.Inthatcase,youmightwanttoturnoffanimationssothatthecorefunctionalitystillworks.The$.fx.offflagisaread/writeflag.Theremainingpredefinedflagsaremeanttoberead-only.Let’stakealookattheflagthatgivesusinformationontheenvironmentprovidedbytheuseragent(browser).DetectinguseragentsupportThankfully,almostblissfully,thejQuerymethodsthatwe’veexaminedsofarshieldusfromhavingtodealwithbrowserdifferences,evenintraditionallyproblematicareaslikeeventhandling.Butwhenwe’retheoneswritingthesemethods(orotherextensions),wemayneedtoaccountforthedifferencesinthewaysbrowsersoperatesothattheusersofourextensionsdon’thaveto.BeforewediveintoseeinghowjQueryhelpsusinthisregard,let’staalbkoutthewholeconceptofbrowserdetection.WHYBROWSERDETECTIONISHEINOUSOK,maybethewordheinousistoostrong,butunlessit’sabsolutelynecessary,thebrowserdetectiontechniqueshouldbeavoided.Browserdetectionmightseem,atfirst,likealogicalwaytodealwithbrowserdifferences.Afterall,it’seasytosay,“IknowwhatthesetofcapabilitiesofbrowserXare,sotestingforthebrowsermakesperfectsense,right?”Butbrowserdetectionisfullofpitfallsandproblems.Oneofthemajorargumentsagainstthistechniqueisthattheproliferationofbrowsers,aswellasvaryinglevelsofsupportwithinversionsofthesamebrowser,makesthistechniqueanunscalableapproachtotheproblem.Youcouldbethinking,“Well,allIneedtotestforisInternetExplorerandFirefox.”ButwhywouldyouexcludethegrowingnumberofSafariusers?WhataboutOperaandGoogle’sChrome?Moreover,therearesomeniche,butnotinsignificant,browsersthatsharecapabilityprofileswiththemorepopularbrowsers.Camino,forexample,usesthesametechnologyasFirefoxbehinditsMac-friendlyUI.AndOmniWebusesthesamerenderingengineasSafariandChrome.There’snoneedtoexcludesupportforthesebrowsers,butitisaroyalpaintohavetotestforthem.Andthat’swithoutevenconsideringdifferencesbetweenversions—IE6,IE7,andIE8,forexample.Yetanotherreasonisthatifwetestforaspecificbrowser,andafuturereleasefixesthatbug,ourcodemayactuallystopworking.jQuery’salternativeapproachtothisissue(whichwe’lldiscussinthenextsection)givesbrowservendorsanincentivetofixthebugsthatjQueryhasworkedaround.Afinalargumentagainstbrowserdetection(orsniffing,asit’ssometimescalled)isthatit’sgettingharderandhardertoknowwho’swho.Arowsersidentifythemselvesbysettingarequestheaderknownastheuseragentstring.Parsingthisstringisn’tforthefaint-hearted.Inaddition,manybrowsersnowallowtheiruserstospoofthisstring,sowecan’tevenbelievewhatittellsusafterwedogothoughallthetroubleofparsingit!AJavaScriptobjectnamednavigatorgivesusapartialglimpseintotheuseragentinformation,butevenithasbrowserdifferences.Wealmostneedtodobrowserdetectioninordertodobrowserdetection!Stopthemadness!BrowserdetectionisImprecise,accidentallyblockingbrowserswithinwhichourcodewouldactuallyworkUnscalable,leadingtoenormousnestedifandif-elsestatementstosortthingsoutInaccurate,duetousersspoofinguseragentinformationObviously,we’dliketoavoidusingitwheneverpossible.Butwhatcanwedoinstead?WHA’ST THEALTERNATIVETOBROWSERDETECTION?Ifwethinkaboutit,we’renotreallyinterestedinwhichbrowseranyoneisusing,arewe?Theonlyreasonwe’reeventhinkingaboutbrowserdetectionissothatwecanknowwhichcapabilitiesandfeatureswecanuse.It’sthecapabilitiesandfeaturesofabrowserthatwe’rereallyafter;usingbrowserdetectionisjustaham-handedwayoftryingtodeterminewhatthosefeaturesandcapabilitiesare.Sowhydon’twejustfigureoutwhatthosefeaturesareratherthantryingtoinferthemfromthebrowseridentification?Thetechniqueknownbroadlyasfeaturedetectionallowscodetobranchbasedonwhethercertainobjects,properties,orevenmethodsexist.Let’sthinkbacktochapter4oneventhandlingasanexample.Rememberthattherearetwoadvancedevent-handlingmodels:theW3CstandardDOMLevel2EventModelandtheproprietaryInternetExplorerEventModel.BothmodelsdefinemethodsontheDOMelementsthatallowlistenerstobeestablished,buteachusesdifferentmethodnames.ThestandardmodeldefinesthemethodaddEventListener(),whereastheIEmodeldefinesattachEvent().Usingbrowserdetection,andassumingthatwe’vegonethroughthepainandaggravationofdeterminingwhichbrowserisbeingused(maybeevencorrectly),wecouldwritecomplexcodetosetflags:isIE,isFirefox,andisSafariif(isIE){element.attachEvent('onclick',someHandler);}elseif(isFirefox||isSafari){element.addEventListener('click',someHandler);}else{thrownewError('eventhandlingnotsupported');}Asidefromthefactthatthisexampleglossesoverwhatevernecessarilycomplexcodewe’ruesingtosettheflagsisIE,isFirefox,andisSafari,wecan’tbesureiftheseflagsaccuratelyrepresentthebrowserbeingused.Moreover,thiscodewillthrowanerrorifusedinOpera,Chrome,Camino,OmniWeb,orahostofotherlesser-knownbrowsersthatmightperfectlysupportthestandardmodel.Considerthefollowingvariationofthiscode:if(element.attachEvent){element.attachEvent('onclick',someHandler);}elseif(element.addEventListener){element.addEventListener('click',someHandler);}else{thrownewError('eventhandlingnotsupported');}Thiscodedoesn’tperformalotofcomplex,andultimatelyunreliable,browserdetection,anditautomaticallysupportsallbrowsersthatsupporteitherofthetwocompetingeventmodels.Muchbetter!Featuredetectionisvastlysuperiortobrowserdetection.It'morereliable,anditdoesn'accidentallyblockbrowsersthatsupportthecapabilitywe'retestingforsimplybecausewedon'knowaboutthefeaturesofthatbrowser,orevenofthebrowseritself.DidyouaccountforGoogleChromeinyourmostrecentwebapplication?iCab?Epiphany?Konqueror?NOTEEvenfeaturedetectionisbestavoidedunlessabsolutelyrequired.Ifwecancomeupwithacross-browsersolution,itshouldbepreferredoveranytypeofbranching.Butassuperiortobrowserdetectionasfeaturedetectionmaybe,itcanstillbenowalkinthepark.Branchinganddetectionofanytypecanstillbetediousandpainfulinourpages,andsomefeaturedifferencescanbedecidedlydifficulttodetect,requiringnontrivialordownrightcomplexchecks.jQuerycomestoouraidbyperformingthosechecksforusandsupplyingtheresultsinasetofflagsthatdetectthemostcommonuseragentfeaturesthatwemightcareabout.THEJQUERYBROWSERCAPABILITYFLAGSThebrowsercapabilityflagsareexposedtousaspropertiesofjQuery'$.supportobject.Table6.1summarizestheflagsthatareavailableinthisobject.The$.supportbrowsercapabilityflagsFl曜property DescriptionImodel'Settoif憧user哪Mrendersaccotiir?Idthe把施dsraiplianlboxmodel.Ihisflafisn'tsetuntilthedocunentisready.Moreifitaa'jwiregardirj(hemunodelissueisavailableathttp7傾邛%涮)de.o回謝加工怔肺andathttp/m.i3jx&TRRECCSWttmLcss*1cilSeitoifthestandartpfosrtyoftheelenot'ss:ylepropertyisusrt.FlagpropertyDescriptionboxModelcssFloatSettotrueiftheuseragentrendersaccordingtothestandards-compliantboxmodel.Thisflagisn'setuntilthedocumentisready.Moreinformationregardingthebox-modelissueisavailableathttp:///css/box.htmlandathttp:〃/TR/RECCSS2/box.html.SettotrueifthestandardcssFloatpropertyoftheelement'stylepropertyisused.Table6.1The$.supportbrowsercapabilityflags(continued)FlagpropertyDescriptionhrefNormalizedSettotrueifobtainingthehrefelementattributesreturnsthevalueexactlyasspecified.htmlSerializeSettotrueifthebrowserevaluatesstylesheetreferencesby<link>elementswheninjectedintotheDOMviainnerHTML.leadingWhitespaceSettotrueifthebrowserhonorsleadingwhitespacewhentextisinsertedviainnerHTML.noCloneEventSettotrueifthebrowserdoesnotcopyeventhandlerswhenanelementiscloned.objectAllSettotrueiftheJavaScriptgetElementsByTagName()methodreturnsalldescendantsoftheelementwhenpassed"*"opacitySettotrueifthebrowsercorrectlyinterpretsthestandardopacityCSSproperty.scriptEvalSettotrueifthebrowserevaluates<script>blockswhenthey'rnjectedviacallstotheappendChild()orcreateTextNode()methods.styleSettotrueiftheattributeforobtainingtheinlinestylepropertiesofanelementisstyle.tbodySettotrueifabrowserdoesn'automaticallyinsert<tbody>elementsintotableslackingthemwheninjectedviainnerHTML.showsthevaluesforeachoftheseflagsforthevariousbrowserfamilies.Browserresultsforthe$.supportflagsAwb*(Fwfes.1WebKitQpflwE3聲*a1EE-QinvnodCiLfubmAndMltimdtCaAftmite.匚wL4rU4ITA1,BAtrue33raisflig電EFU*kirvtfAlVflLniAhruakru?(tlB*o叼■ulJU1Ln?Lrua口自鼻ElLJrLFuq上 1rfe.tl-UQ.UnaLtIjsEa1■atriisi-U.C:Umtruiiitru*truflAsexpected,itcomesdowntothedifferencesbetweenInternetExplorerandthestandards-compliantbrowsers.Butlestthislullyouintothinkingthatyoucanjustfallbackonbrowserdetection,thatapproachfailsmiserablybecausebugsanddifferencesmaybefixedinfutureversionsofIE.Andbearinmindthattheotherbrowsersaren'immunefrominadvertentlyintroducingproblemsanddifferences.Featuredetectionisalwayspreferredoverbrowserdetectionwhenweneedtomakecapabilitydecisions,butitdoesn'alwayscometoourrescue.Therearethoseraremomentswhenwe'needtoresorttomakingbrowser-specificdecisionsthatcanonlybemadeusingbrowserdetection(we'llseenexampleinamoment).Forthosetimes,jQueryprovidesasetofflagsthatallowdirectbrowserdetection.6.1.3ThebrowserdetectionflagsForthosetimeswhenonlybrowserdetectionwilldo,jQueryprovidesasetofflagsthatwecanuseforbranching.They'reetupwhenthelibraryisloaded,makingthemavailableevenbeforeanyreadyhandlershaveexecuted,andthey'reefinedpropertiesofanobjectinstancewithareferenceof$.browser.NotethateventhoughtheseflagsremainpresentinjQuery1.3andbeyond,they'regardedasdeprecated,meaningthattheycouldberemovedfromanyfuturereleaseofjQueryandshouldbeusedwiththatinmind.Theseflagsmayhavemademoresenseduringtheperiodwhenbrowserdevelopmenthadstagnatedsomewhat,butnowthatwe'venteredanerawhenbrowserdevelopmenthaspickedupthepace,thecapabilitysupportflagsmakemoresenseandarelikelytostickaroundforsometime.Infact,itrecommendedthat,whenyouneedsomethingmorethanthecoresupportflagsprovide,youcreatenewonesofyourown.Butwe'Igettothatinjustabit.Thebrowsersupportflagsaredescribedintable6.3.Notethattheseflagsdon'attempttoidentifythespecificbrowserthat'sbeingused.jQueryclassifiesauseragentbaseduponwhichfamilyofbrowsersitbelongsto,usuallydeterminedbywhichrenderingengineituses.Browserswithineachfamilywillsportthesamesetsofcharacteristics,sospecificbrowseridentificationshouldnotbenecessary.;ru■ifw-EiiiEirnliri!?t|■■小theHisbawdiRdijdM ipHimCGiftm■■后打 EgLruttICh manycMth?WhtMdl口i?drivfi”Him?Chrwinnhd口fthWnkS*4IeLru4i1IKeu*efit <hOr%SetIeitfw*piLTih-PFthseMiterag.meeTmthebrewsw.Table6.3The$.browseruseragentdetectionflagsFlagpropertyDescriptionmsieSettotrueiftheuseragentisidentifiedasanyversionofInternetExplorer.mozillaSettotrueiftheuseragentisidentifiedasanyoftheMozilla-basedbrowsers.ThisincludesbrowserssuchasFirefoxandCamino.safariSettotrueiftheuseragentisidentifiedasanyoftheWebKit-basedbrowsers,suchasSafari,Chrome,andOmniWeb.operaSettotrueiftheuseragentisidentifiedasOpera.versionSettotheversionnumberoftherenderingengineforthebrowser.Thevastmajorityofcommonlyused,modernbrowserswillfallintooneofThesefourbrowserfamilies,includingGoogleChrome,whichreturnstrueforthesafariflagduetoitsuseoftheWebKitengine.Theversionpropertydeservesspecialnoticebecauseit'notashandyaswemightthink.Thevaluesetinthispropertyisn'theversionofthebrowser(aswemightinitiallybelieve)buttheversionofthebrowser'srenderingengine.Forexample,whenexecutedwithinFirefox3.6,thereportedversionis1.9.2—theversionoftheGeckorenderingengine.ThisvalueishandyfordistinguishingbetweenversionsofInternetExplorer,astherenderingengineversionsandbrowserversionsmatch.Wementionedearlierthattherearetimeswhenwecan’tfallbackonfeaturedetectionandmustresorttobrowserdetection.Oneexampleofsuchasituationiswhenthedifferencebetweenbrowsersisn’tthattheypresentdifferentobjectclassesordifferentmethods,butthattheparameterspassedtoamethodareinterpreteddifferentlyacrossthebrowserimplementations.Insuchacase,there’snoobjectorfeatureonwhichtoperformdetection.NOTEEveninthesecases,it’spossibletosetafeatureflagbytryingtheoperationinahiddenareaofthepage(asjQuerydoestosetsomeofitsfeatureflags).Butthat’snotatechniqueweoftenseeusedonmanypagesoutsideofjQuery.Let’staketheadd()methodof<select>elementsasanexample.It’sdefinebdytheW3Casfollows(at/TR/DOM-Level-2-HTML/html.html#ID-14493106,forthoseofuswholiketolookatthespecifications):selectElement.add(element,before)Forthismethod,thefirstparameteridentifiesan<option>or<optgroup>elementtoaddtothe<select>elementandthesecondidentifiestheexisting<option>(or<optgroup>)beforewhichthenewelementistobeplaced.Instandards-compliantbrowsers,thissecondparameterisareferencetotheexistingelementasspecified;inInternetExplorer,however,it’sthoerdinalindexoftheexistingelement.Becausethere’snowtaoyperformfeaturedetectiontodeterminewhetherweshouldpassanobjectreferenceoranintegervalue(shortoftryingitout,asnotedpreviously),wecanresorttobrowserdetection,asshowninthefollowingexample:varselect=$('#aSelectElement')[0];select.add(newOption('Twoand\u00BD','2.5'),$.browser.msie?2:select.options[2]);Inthiscode,weperformasimpletestofthe$.browser.msieflagtodeterminewhetherit’sappropriatetopasstheordinalvalue2,orthereferencetothethirdoptioninthe<select>element.ThejQueryteam,however,recommendsthatwenotdirectlyusesuchbrowserdetectioninourcode.Rather,it’srecommendedthatweabstractawaythebrowserdetectionbycreatingacustomsupportflagofourown.Thatway,shouldthebrowsersupportflagsvanish,ourcodeisinsulatedfromthechangebymerelyfindinganotherwaytosettheflaginonelocation.Forexample,somewhereinourownJavaScriptlibrarycode,wecouldwrite$.support.useIntForSelectAdds=$.browser.msie;andusethatflaginourcode.Shouldthebrowserdetectionflageverberemoved,we’donlyhavetochangeourlibrarycode;allthecodethatusesthecustomflagwouldbeinsulatedfromthechange.Let’snowleavetheworldofflagsandlookattheutilityfunctionsthatjQueryprovides.Listing6.1Readyhandlertest1<!DOCTYPEhtml><html><head><title>Hi!</title><scripttype="text/javascript"src="../scripts/jquery-1.4.js"></script><scripttype="text/javascript">var$='Hi!';Overrides$namejQuery(function(){DeclarestheCBwithcustomvaluealert('$='+$);readyhandler});</script></head><body></body></html>Inthisexample,weimportjQuery,which(asweknow)definestheglobalnamesjQueryanditsalias$.Wethenredefinetheglobal$variabletoastringvalueB,overridingthejQuerydefinition.Wereplace$withasimplestringvalueforsimplicitywithinthisexample,butitcouldberedefinedbyincludinganotherlibrarysuchasPrototype.WethendefinethereadyhandlerCwhoseonlyactionistodisplayanalertshowingthevalueof$.Whenweloadthispage,weseethealertdisplayed,asshowninfigure6.1.Notethat,withinthereadyhandler,theglobalvalueof$isinscopeandhastheexpectedredefinedvalueresultingfromourstringassignment.HowdisappointingifwewantedtousethejQuerydefinitionof$withinthehandler.Nowlet'makeonechangetothisexampledocument.Thefollowingcodeshowsonlytheportionofthedocumentthathasbeenmodified;theminimalchangeishighlightedinbold.(Youcangetthefullpageinchapter6/ready.handler.test.2.html.)<scripttype="text/javascript">var$='Hi!';jQuery(function($){alert('$='+$);});</script>Figure6.1The$says,"Hi"sitsredefinitiontakeseffectwithinthereadyhandler.Ohtrp/」《一 《卜/pgrbrsdy.lian歲事.供$t.?hlmlThtpageal 土加太i-hjAdX,糖kCt削.E4MHT“hIueir4umrMi.Ifrtgfh---07rMiXNfry [jQ^ery歸小。1I■?,mrJMt皿)I C0K)Readghw尸F(xiàn)igure6.2ThealertnowdisplaysthejQueryversionof$becauseRedefinitionhasbeenenforcedwithinthefunction.Theonlychangewemadewastoaddaparametertothereadyhandlerfunctionnamed$.Whenweloadthischangedversion,weseesomethingcompletelydifferent,asshowninfigure6.2.Well,thatmaynothavebeenexactlywhatwemighthavepredictedinadvance,butaquickglanceatthejQuerysourcecodeshowsthat,becausewedeclarethefirstparameterofthereadyhandlertobe$withinthatfunction,the$identifierreferstothejQueryfunctionthatjQuerypassesasthesoleparametertoallreadyhandlers(sothealertdisplaysthedefinitionofthatfunction).Whenwritingreusablecomponents,whichmightormightnotbeusedinpageswhere$.noConflict()isused,it'besttotakesuchprecautionsregardingthedefinitionof$.AgoodnumberoftheremainingjQueryutilityfunctionsareusedtomanipulateJavaScriptobjects.Let'takeagoodlookatthem.譯文:JQuery標(biāo)簽的使用至此,我們花了相當(dāng)多的章節(jié)審查了 jQuery方法對一組元素的DOM?作所包裹的 $()函數(shù)。但是你可能還記得 ,早在第一章中,我們還推出了概念效用函數(shù)由jQuery的命名空間的功能 / $不作用于一個包裝集。這些功能可以被認(rèn)為是頂級功能,但他們對 $的實例定義 ,而不是窗口的功能,讓他們在全局命名空間之外。一般來說,這些功能或者作用于 JavaScript對象,而不是DOMFE素(這職權(quán)范圍內(nèi)的包裝方法),或者或者執(zhí)行一些非對象相關(guān)的操作(如一個 Ajax請求)。除了功能,jQuery還提供了一些有用的標(biāo)記,用來定義 jQuery/$命名空間。TOC\o"1-5"\h\z你可能想知道為什么我們直到這一章才介紹這些功能和標(biāo)志。我們有兩個理 由:※我們希望引導(dǎo)你使用jQuery的包裝 方法,而不是訴諸于低級別操作, 能你會覺得那是更熟悉的思維,但卻不能有效或容易的使用jQuery代碼包裝。X因為當(dāng)在頁面上操作DOME素的時候,包裝方法大多照顧我們想要做什么,在寫方法本身時這些低級別的功能經(jīng)常是最有用的(以及其他擴展)而 不是在頁面級代碼。(在下一章我們將要 處理如何寫自己的插件給 jQuery)。在這一章節(jié),我們將繞過終于正式推出的 $級別最實用的功能,以及一些有用的標(biāo)志。我們將會推遲談?wù)撎幚?jQuery’sAjax效用函數(shù)特 別強調(diào) Ajax的功能性的第 8章。我們從那些我們提到的那些 flags開始。使用jQuery的重點一些jQuery提供的信息使像我們網(wǎng)頁 制作者,甚至外掛程序作者,可用的不通過方法或功能而通過屬性定義 $。這些很多flags集中幫我們探測當(dāng)前瀏覽器的情況,而其他的幫我們控制全局頁面水平的jQuery的水平。為公眾開發(fā)的Queryflags的使用如下:$.fx.off—不能使用的效果$.support—支持細(xì)節(jié)的特征$.browser—暴露瀏覽器的細(xì)節(jié) (正式不支持)讓我們開始看看 jQuery如何使我們禁用動畫。動畫的禁用可能會有很多次我們可能想有條件地在包括各個動畫效果的一個頁面禁用動畫。我們可以這樣做因為我們檢測了那個平臺或設(shè)備不會很好地處理他們。如果是那樣,我們不需要采取寫兩頁,一頁有動畫一頁沒有的形式。當(dāng)我們檢測我們在一個 animation-adverse環(huán)境時,我們可以簡單地把$.fx.off的值設(shè) 成真。這不會影響我們使用頁面 ;它將簡單地 禁用那些的動畫效果。例如,平凡的 效果能在不用干預(yù)動畫的情況下立即展示和隱藏原理。同樣地,通過 animate()方法能設(shè)置樣式表文件屬性成特定的最終的值。一個可能的使用這個 flag的情況是對于某些移動設(shè)備或瀏覽器不能正確地支持動畫。在這種情況下,你可能 想關(guān)掉動畫以便核心功能性仍然的工作。$.fx.offflag是一個讀/寫flag。一直被預(yù)定義的flag只能只讀。讓的看一下提供給我們關(guān)于環(huán)境由規(guī)定用戶代理 (瀏覽器)的信息的flag。檢測用戶代理支 持感激幾乎開心的是,我們審查了到目前為止保護我們從不得不處理瀏覽器差異的jQuery方法,即使在傳統(tǒng)地有 問題的地方喜歡事件處理。但是當(dāng)我們一寫這些方法 (或其他的擴展類 ),我們需要說明法我們的擴展類的用戶不得不運行瀏覽器差異。在我們看jQuery在這方面如何幫助我 們,讓我們談?wù)撘幌聻g覽器檢測的整個概念。為什么瀏覽器檢測是可恨的?好的,也許可恨這個詞太強烈,但除非它是必不可少,瀏覽器檢測技術(shù)將避免使用。瀏覽器檢測可能似乎,首先,像一個合乎邏輯的方法處理瀏覽器差異。然而,簡單的說“我知道什么是瀏覽器的能力射線異物檢查裝置,因此測試瀏覽器很有意義,對嗎 ?”然而瀏覽器檢測 充滿陷阱和問題。主要針對這技術(shù)論點之一是,擴散的瀏覽器,以及變化支持層次內(nèi)同一的版本瀏覽器,使這技術(shù)一個無法解決的問題。你可能會想,“好的,我需要測試的是 InternetExplorer和Firefox。”但是為什么你排除增長著的Safari用戶的數(shù)量?那Opera和Google’sChrome呢?而且,有一些定位,但并不微不足道,分析更受歡迎瀏覽器。例如,用同一技術(shù)像 Firefox背后它的mac-friendly用戶界面。沒有必要撤銷對這些瀏覽器的支持,但是不得不測試。而且不用考慮在版本之間—例如IE6,IE7,IE8的差異。然而另一個原 因是,如果我們測試一個具體瀏覽器,一個未來的版本固定那個竊聽器,那么我們的代碼可能其實停止工作。jQuery’s選擇解決問題的方法(我們將在接下來的部分討論 )給瀏覽器一個提示來固定 jQuery圍繞工作的竊聽器。一個最后針對瀏覽器檢測的論點是知道誰是誰變得越來越困難了。瀏覽器支持自己附近的一個請求頭被稱為用戶代理串。解析這個串不是很TOC\o"1-5"\h\z讓人害怕。除此之外,許多瀏覽器現(xiàn)在允許他們的用戶欺騙這個串,所以我 們甚至不能相信它告訴我們的盡管解析它很麻煩 !一個以航海家命名的JavaScript給我 們了解到用戶代理信息的一部分,然而甚至它有瀏覽器差異。我們幾乎需要為了瀏覽器檢測而去做瀏覽器檢測!停止這瘋狂的事 !瀏覽器檢測是不精確,在我們的代碼運行,導(dǎo)致巨大的漏洞ifandif-else語句聲明的偶然阻止瀏覽器 ?不精確的,由于用戶欺騙用戶代理信息。顯然,我們要盡可能避免使用它。但是我們又能做什么來替代呢?有什么可替代瀏覽器檢測?如果我們想一想,我們不是真的感興趣哪個人在使用瀏覽器,是嗎?我們考慮瀏覽器檢測的唯一的理由是我們能知道哪些能力和特征我們能使用。所以為什么我們不只是弄清楚什么那些特征比容易推斷從瀏覽器集成數(shù)字增強型網(wǎng)絡(luò)。特征檢測的技術(shù)允許代碼分支是否為依據(jù)某些的物體,屬性或方法存在。event-讓我們回想章 4在事件處理的一個例子。記得有兩個先進的event-handling模型:W3CstandardDOMLevel2EventModel和InternetExplorerEventModel。兩個模型定義了關(guān)于DOME素允許傾聽者被建立,但用不一樣的方法名稱的方法。標(biāo)準(zhǔn)模型定義了addEventListener()方法,而IE模型定義了attachEvent()。使用瀏覽器檢測,假設(shè)我們經(jīng)過了運行,確定了增加哪個瀏覽器的使用(也許正確地),我們可以寫complexcodetosetflags:isIE,isFirefox, andisSafari...if(isIE){element.attachEvent('onclick',someHandler);}elseif(isFirefox||isSafari){element.addEventListener('click',someHandler);}else{thrownewError('eventhandlingnotsupported');}除了這例子掩蓋復(fù)雜的代碼,我們都將使用既定的flags,是firefox,還是safari,我們不能缺定這些flags是否準(zhǔn)確代表瀏覽器被使用。而且,如果使用Opera,Chrome,Camino,OmniWe
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 《海的女兒》讀后感
- 鄉(xiāng)村醫(yī)生主要先進事跡(6篇)
- 鄉(xiāng)鎮(zhèn)老齡工作總結(jié)范文
- 中秋節(jié)活動心得體會(5篇)
- 新學(xué)期學(xué)習(xí)計劃范例匯編7篇
- 在銀行的實習(xí)報告范文錦集七篇
- 世博會觀后感
- 高等數(shù)學(xué)教程 上冊 第4版 習(xí)題及答案 P146 第6章 定積分及其應(yīng)用
- 幼兒誠信課件教學(xué)課件
- 做好課堂課件教學(xué)課件
- (試卷)建甌市2024-2025學(xué)年第一學(xué)期七年級期中質(zhì)量監(jiān)測
- 2024年企業(yè)業(yè)績對賭協(xié)議模板指南
- “全民消防生命至上”主題班會教案(3篇)
- 2024年海南省高考?xì)v史試卷(含答案解析)
- 2024年湖北武漢大學(xué)化學(xué)與分子科學(xué)學(xué)院招聘1人(實驗中心)歷年高頻難、易錯點500題模擬試題附帶答案詳解
- 24秋國家開放大學(xué)《當(dāng)代中國政治制度》形考任務(wù)1-4參考答案
- “以德育心,以心育德”
- 35kV配電系統(tǒng)調(diào)試試驗方案
- 臨床用藥管理制度
- 多層工業(yè)廠房施工組織設(shè)計#現(xiàn)澆框架結(jié)構(gòu)
- 消防控制室值班記錄(制式表格).doc
評論
0/150
提交評論