Simple and complicated conversion of JS Web page

Source: Internet
Author: User
Tags ming sodium tagname

There are two ways to transform a Web page into a simple font: one is to use professional software such as Jen Fintong, and the other is to make two versions of the Web page. Obviously, both of these methods are cumbersome, and professional software is generally not available for free space. The author here to provide you with a very simple method, only need to add a few lines of code on the page can easily handle the simple transformation of the page.

First download the JS file transform.js for simple and complex conversion:

//*===========================================================================//* (c) Copyright Liqwei//* Email:liqwei (at) liqwei.com//* site:http://www.liqwei.com///*===========================================================================//* Function: Responsible for simple and traditional conversion, need to be placed at the bottom of the page;//* Version: v1.0;//*===========================================================================//function: Convert the object, use recursion, peel the text layer by level;functiontransformcontent (Switcherid, fobj) {if(typeof(fobj) = = "Object"){        varobj=Fobj.childnodes}Else {            if(parseint (fobj)!=0) {//control does not update the current page language state when the page is initialized;            varSwitcherobj =document.getElementById (Switcherid);  with(switcherobj) {if(parseint (Iscurrentft)) {InnerHTML= Innerhtml.replace (' Jane ', ' complex ') Title= Title.replace (' Jane ', ' complex ')                }Else{InnerHTML= Innerhtml.replace (' complex ', ' Jane ')) Title= Title.replace (' complex ', ' Jane '))}} switcherobj.innerhtml=TransformText (switcherobj.innerhtml, Iscurrentft) Switcherobj.title=TransformText (Switcherobj.title, Iscurrentft)if(iscurrentft== "1") {iscurrentft= "0"}Else{iscurrentft= "1"} writecookie ("Iscurrentft", Iscurrentft)} varobj=Document.body.childNodes} for(vari=0;i<obj.length;i++){        varoo=Obj.item (i)if("|| br|hr| Textarea| ". IndexOf ("|" +oo.tagname+ "|") >0| | Oo.id==switcherid)Continue; if(oo.title!= "" &&oo.title!=NULL) oo.title=TransformText (Oo.title, ISCURRENTFT); if(oo.alt!= "" &&oo.alt!=NULL) oo.alt=TransformText (Oo.alt, ISCURRENTFT); if(oo.tagname== "INPUT" &&oo.value!= "" &&oo.type!= "text" &&oo.type!= "hidden") Oo.value=TransformText (Oo.value, ISCURRENTFT); if(oo.nodetype==3) {Oo.data=TransformText (Oo.data, Iscurrentft)}Elsetransformcontent (Switcherid, OO)}}//function: Converts the specified string;functiontransformText (TXT, isft) {if(txt==NULL|| txt== "")return""if(parseint (isft)) {returnS2T (TXT)}Else{returnt2s (TXT)}}//function: Simplified characters to traditional characters;functions2t (cc) {varStr= ", Ss=jtpy (), tt=ftpy ();  for(vari=0;i<cc.length;i++){        varc =Cc.charat (i); if(c.charcodeat (0) >10000&&ss.indexof (c)!=-1) str+=Tt.charat (Ss.indexof (c)); Elsestr+=C; }    returnstr;}//function: The characters of traditional Chinese characters are converted to simplified characters;functionT2s (cc) {varStr= ", Ss=jtpy (), tt=ftpy ();  for(vari=0;i<cc.length;i++){        varc =Cc.charat (i); if(c.charcodeat (0) >10000&&tt.indexof (c)!=-1) str+=Ss.charat (Tt.indexof (c)); Elsestr+=C; }    returnstr;}functionjtpy () {return ' Ai ai in Love, AO-ba-AO-pa-i-tie-to-the-pound----------------------------Jackal warehouse Cang toilet side of the test layer astonished mixed with cicada, slander, scraping, and a long repayment of the bowel factory, Chang-cheng-chen lining of the note-making car to the dust-proof of the late Chi, the shame teeth blazing insects spoil the domain lift Catinaccio raise silk ugly kitchen hoe young infrastructure storage Contact Spread sores Chong Hammer pure words to give Cong chimneys from the clump of the wrong Tatsu Tan Shan gall shishi Christmas bomb when the party swing the Island Prayer guide Thief Light Deng Enemy polyester recursive point Mat electric lake fishing to overlap nail top ingot Set East dynamic building freeze bucket calf read BET plating forged broken satin team to the ton of blunt snatch goose amount of bad hungry son Bait II send a penalty valve alum vanadium annoying fan food visit spinning fei waste fee of the grave Fen Qi Feng Feng qi Feng Feng sewing irony Phoenix skin Touch Fu Fu Complex negative obituary women tie the calcium Gaigan to drive the stem Gan Gang steel gang Gao Hao shelf pigeon ge chromium to Shing Gong hook ditch to buy enough tricky Gu Guan Guan Hall customs wide regulation silicon to the turtle, the Ark of your executioner roll the country over terrible Han Hanyu crane He Heng Bang Hung red after the pot protection Hu Hua painting strokes words Huai Huan ring also slow change call body Huan Huan yellow lie wave destroy bribe will stew taboo to paint dirty gang get goods disaster hit machine accumulate hunger ridiculed chicken performance of the grade squeeze a few The Thistle-ji's notes on the record of the Ji-wei Jia potassium price driving the struggle between the hard sealed cocoon inspection alkali pick Jiang reduction recommended sill practice base See key ship sword preserves gradually splash jian pulp jiang Paddle award sauce glue pouring arrogance jiao stir hinge straightening after blast foot dumplings pay stranded the car is more than the straw section stem startled by the neck static mirror diameter of the old colt lifting according to the saw fear play Juan Silk Jie Jie the knot of the commandments tight Kam only to enter the Jin Ember all the way to the absolute June June Kai Shell lesson Ken to pull out the bank pants boast Block executioner wide mining conditions deficit kui peek feed-off widening wax La Lai lai blue bar stop Lan calumniate The lazy cable rotten fishing Lao le Lei Lei lei li Li 厉励砾 calendar lek two Lian Lian even sickle-pity ripple curtain convergence face chain love to practice grain cool two of the handcuffs of the game of the rental-lin-ling-Linglingling-ming-ling-ming-ling-Liu Long deaf throat Cage Ridge long Lou Lou hug Basket lu Lu Skull LU Furnace captive to the Ruthero record Land Donkey LU Aluminum lu filter Green The luanhe of the Luan Twins, Lun Lun, Luo luo luo, the horse Luo ma ma code ma horses scold? Buy wheat sell mai pulse deceive steamed bread pretty full them cat anchor riveting trade mold no magnesium door stuffy manganese dream puzzle find cotton Burma temple to kill Min Ming-ming-mu-na sodium na hard to scratch the brain annoyed hungry tired of twisting stuffed bird Nie nickel lime Caracal ning Twist Nim button new pus rich agricultural malaria Connaught Ouchi beating vomit retting disk Pang Love compensate spray peng cheat floating frequency poor apple with the evaluation pour quite flutter spread the spectrum of the umbilical Qi ride Do not start the gas abandon the draft of the lead in the transfer of money pliers shallow cut gun choke wall Qiang strong grab shovel bridge Joe to steal Chin Pro light hydrogen pour is please qing June poor trend area body drive caries zygomatic right advised but magpie let annoying around hot tough recognize thre rong Velvet soft sharp leap run sprinkle the gill race umbrella bereavement sweep astringent kill yarn screen flash Shaanxi allowance injury to burn Shaoxing credit to the judge of the Shen trial of the kidney infiltration sound rope sheng Master Lion wet poem Corpse time erosion knowledge driving potential release decoration view trial Life Beast armature transmission book redemption Operation Tree vertical number handsome double who tax shun said Shuo Shuo Silk feed shrugged Somo Su although sui old sun damage shoot shrinking lock Rex tart lift spread greed paralysis beach altar tan talk sigh soup hot tao sash copy antimony question body Drawer Iron Hall Listen hydrocarbon copper head figure coating Group decadent shed camel Tuo oval socks Bend Wan Stubborn Wan Wei Wai Wei Wei Wei Wen the false weft to hear the grain stability asked urn Laos volute vortex hole framed Wu Wan fog false tin sacrifice attack XI Milling play fine shrimp jurisdiction Xia man narrow xia shovel fresh fiber Xian Xian Yin title Xianxian Filling Envy The Constitution of the Line box set township detailed ring Xiao Pin Xiao Sao Scorpion AssociationCarrying threatening harmonic writing Xie zinc Peacemaker hing feign rust embroidery Xu Xu Yu continued Xuan selected ringworm gorgeous learn to find training the pressure Crow duck dumb ya surprised to smoke salt Yan Yan Yan tired Yan Yang Yao Yan duck Yang Yang-yao yao kiln ballad medicine ye ye leaf medical iridium yi yi yu ant yi zhi yi zhi xuan yi Yi Yin Silver drink sakura Baby Eagle Ching Firefly Ying Flies Ying-fu Carbuncle Chant Yong Chung gifted worry postal uranium still swim lure fish Yu and Yu The shafts of the prison reputation pre-yu Yuen Yuan Garden staff round edge is willing to around the key Yue Yue read Cloud Yunyang evenly meteorite Yun Yun Wine together Ltd Halo Rhyme Miscellaneous Disaster load Save temporary praise Dirty chisel jujube stove responsible Choice ze thief gift guillotine brake fraud Zhai debt felt lamp chop precipitous peak stack war split Zhang rise account swelling Zhao switch GE This zhen-pin detective town to earn open by frame Zheng Card Weaving professional paper, the quality clock finally kind of swelling all the hair shaft wrinkle Day sudden pig all the candle visions will be storage cast built in special brick to earn pile Zhuang Put on the makeup of the cone-shaped Zhun mang turbidity of the total longitudinal 邹诅 Group of drilling Zhong for only the fierce quasi-kai plate Gimli more chain vent ';}functionftpy () {return ' Backup 藹 failover Fusuma Dams Strikes defeat proceed awards office Bond help kidnapped pound 謗: 'd saturated Bao Bob my life Bay diacetate stumble prepare tired tightness pen shot close up descended change argued flowers 鼈 message endangered waterfront 擯 cookies flick mortar platinum Mahaina carrot supplement a cruel ashamed dire hotel sunroute Hitomi Hatch 滄州市 WC surprised guarantees blended cicadas 饞 讒 tangles Work Spade factory makes trembling station compensated gut plants few laps money car all dust Chen lined appropiate Honest battlefield going crazy late Gucci Chee Insect Pet categories waver organising silky ugly closet kitchen She 菢雛之窩 Biography piles broke creative weights pure Dolcevita resignation words grant smart onions chimneys from jungle Minatomachi River break wrong belt loaned worry 邯鄲市 Shan dreaded the retainer party 蕩 pounding island Prayer pirate light Tang enemy washing parties point mattress power starch fishing adjust mole overlay nail top Spindles subscribe East Nicholas Frozen fight bullpup plated steel forgings satin confirmed team to ton dull capture swan blackmail evil hungry son lures Daini the punishment valve 琺 礬 bangtong trouble Sellers Hotel visit Marl Sleepsac Colorful Cemetery Feng fan anger Dung Maple Feng Feng Sewing The talent of the ironic Obituaries Bondage The calcium cover the statue synopsis mound Gao pickaxes stranded pigeons-chromium-龔-strengthening-a-propaganda-to-the-efficiency-the-剮-consistent-and-turtle-the-bedroom------tricks barriers Tsurumi bomber hung pot protection s Wooh Hua painting, the destruction of the environment and also the paralyzed Longoza 渙 the yellow lie, bribery out ragout conceal depiction, utilization awful, accidents hit hunger, CANopen, Warrant, Artichokes, pod cheeks, potassium, destroyers, 箋 grueling bite, cocoon alkali alkaline chosen simplified pick thrifty threshold draw practices see key warships cheap gradually 餞 splash as syrup jing Awards soy sauce Paddle watering proud club cubic stirring hinge bulb pacifier foot amongst dumplings winch sedan chaff stage penis amazing décolleté meditation reduces competition correcting manger old Capsule Inn according to saw Azalea Silk Commandments ACADEMY in Kan Kuching Ashes unmotivated Negundo sincerity Nick the Tsun shell the Kenting in the course of his experience. Block snobbish Mineral Kuang case Thanks 巋 glimpse feedback bulb expansion width wax roast Raleigh blue Linked fields suspend basket appendicitis Guanlan 淀粉质 recruited browse lazy accord rotten abuses anotherjob labor 澇 music beam softball tears fences leave delivering gift Hanja calendar asphalt synchronicity Lian Lian Scythe poor ripples curtain 斂 face chain Alchemy Dept Cool two forgive Liao 鐐 hunting neighbor Scales Luv rentals Age Ling Davis Pok leader distillation Lau Dragon deaf throat cage monopolistic alongside 隴 floor bellow held 簍 Aloe rupee cranial bailu stove captured 鹵 captive bribery Pauline record donkey lui Che Woo aluminum partners robust Hamamelis considering discard Green Severn 攣 孿 pedestrians chaos stall the rurunrun boundary lun turnip logically gong 籮 騾 Mary's code camel Macedonian 螞蟻 to buy the Miami scoid cheat 饅 meet somewhat cat 謾 anchors trade mold riveting magnesium boring dream Mangan mystery Praya foraging shrine extinction sponge Sacramento Mercy Hokkien absurdity conspiracy acre sodium harass brain worries stop! Discouraged blockages scumbags twist stuffed birds nien notable ã isotopes lemon 獰 ning screwed dirt button newport abscesses concentration malarial Boliviano seagulls punch vomit 漚 tray Bond love sue spray pang cheat fluttering video poorer apple procured reviews spill undesired poker frontage rustic belly Wouldn't Kai 訖 towed 扡 brazing pencil climate signed 謙賢 money fangs potential shallow condemnatory 竹塹社 gun back wall at Hog Haft Bridge Joe Beyo dead tricks theft kitchener gently hydrogen hectares please qiong poor trend Torso 齲 zygomatic the right advise Choquette let spare disturb the firmware sewing soft sharp rinjita sprinkled gills, umbrella, harassment Shibuya kill yarn Screening herbs blink Shaanxi 贍 Renovation damage to the tick deterrent JP aunts the kidney infiltration offenders The Master lion the corpse eclipses the knowledge of the centrum of the game Atonement Erector spinae number handsome double who tax said Masters flashing fan dietary towering 慫 Kwan litigation chant administration Sue Hanzi Although Tuy hoa years Sampathkumar shoot tedious lock otter à Eben booth greedy emotionally beach altar tan talk Marvel Tom boiling Wentao 縧 totem ESO diantimony topic drawer The alkanes head of the group 頹 transformation Ostrich Sendagaya Camels elliptical orbits Miyakubo Sock Bend Wan Naughty the Nanhuan endeavor Latitude Wei Wen Wen texture stability asked difference urn Laos 蝸 swirl nest oooo Ugandan tungsten no 誣 above Wu Hollywood mission cloudy Siena attack sacrifices play edged krill Canyon Batman narrowness mansion 鍁 Fresh fiber Salt Yin titles casual The present county Pies Envy Constitution line compartments set Village details Siu Hyo Tsunami accountGimps Carrying threat Harmony write 瀉肚 thank zinc provocative happy choppy rusty embroidery virtual Shh! Have to continue Xuan sowing choose Archive Florid Learning Medal search tame training Raven duck mute asian surprise oxen smoke salt strict liben canary hate Yangmingshan Kōmura Proverbs experience Brede Yang part itch remote kiln Rumors Royal medicine Iridium detected heritage 彜 ants art memory hatsumode friendship translation become shade Sakura Eagle Baby 纓 leytoneric Fluorescence the camp flies stand yo maid embrace 癰 participative wing worries flood lure mail discussion fishing fish Entertainment and Lantau Island The Merquise 鴛 Mabuchi 轅 Park member of the circle is willing to jump keys Rokkei Cantonese Joy Cloud 鄖 uniform scientist pendant eradicated Dizzy Wan Leng miscellaneous 攢 temporary hostage dirty è-ovens responsibility thief giveaway put down byronin gin  shutter Scams fasting debt felt beacon Tad could brand Rainbow Love Zhang Coleman account mega Hyperinflationary Zhao 驚蟄 deal germanium This Jung Needle diagnostic array struggling opened 猙 frame 鄭 certification paper sincere sidearm of flags quality Chung finally swelling congregation scholarly axis wrinkled daylight the pork 誅 candles Cinder Testament Lagoon cast architecture consulate in Brick Makeup Erlenmeyer flask Baggage falling able ipmi conjugation the marinade CI The Mr. Zou cursed group Diamond so killer in the Perak of the boss.;}//function: Gets the Cookie value of the specified name;functionReadcookie (name) {varValue = ""; if(Document.cookie.length > 0){      varprefix = name + "="; varBegin =document.cookie.indexOf (prefix); if(Begin! =-1) {begin+=prefix.length; varEnd = Document.cookie.indexOf (";", begin); if(end = =-1) end =document.cookie.length; Value=unescape (document.cookie.substring (begin, end)); }  }  returnvalue;}//function: Set the Cookie value of the specified name;functionWritecookie (name, value, days) {varargv =writecookie.arguments; varARGC =writeCookie.arguments.length; varDays = (argc>2)? Argv[2]:NULL; if(days!=NULL){        varExpireDate =NewDate (); Expiredate.settime (Expiredate.gettime ()+ (days*1000*3600*24)); } document.cookie= name+ "=" +escape (value) + ((days==NULL)?"":("; Expires= "+expiredate.togmtstring ())) +"; path=/";}varIscurrentft;//function: page initialization function//switcherid text link, click to be responsible for simple and complex switch, suggestion: <a id= "Switcher_link" href= "#" > Traditional Chinese </a>;//Isdefaultft whether the current document defaults to traditional Chinese;//delay time after page load, unit milliseconds;//Cookie variable name used: Iscurrentftfunctioninitpagelanguage (Switcherid, ISDEFAULTFT, delay) {Isdefaultft= Isdefaultft? " 1 ":" 0 "; varswitcherobj=document.getElementById (switcherid) Iscurrentft=readcookie ("Iscurrentft")    if(iscurrentft==NULL|| iscurrentft== "") iscurrentft=Isdefaultft with(switcherobj) {if(typeof(document.all)! = "Object") {//non-IE browserhref= "Javascript:transformcontent ('" + Switcherid + "');        }Else{href="#"; OnClick=NewFunction ("Transformcontent ('" + Switcherid + "); return false;")        }        if(title = =NULL|| title== "") title = "Click to browse in Traditional Chinese way"; if(parseint (Iscurrentft)) {InnerHTML= Innerhtml.replace (' complex ', ' Jane ')) Title= Title.replace (' complex ', ' Jane '))} InnerHTML= TransformText (InnerHTML, parseint (ISCURRENTFT)? 0:1) Title= TransformText (title, parseint (ISCURRENTFT)? 0:1)    }            if(ISCURRENTFT!=ISDEFAULTFT) {SetTimeout ("transformcontent ('" + Switcherid + "', 0)", Delay)}}//initializing the Calling interface//initpagelanguage ("Switcher_link", false, +);

Copy to the Site directory, and then use the Web authoring tool to open the Web page that needs to be converted, adding the following code to the code:

Error before using OBJ.INNERHTML=S2T (obj.innerhtml): Unable to get property ' InnerHTML ' of undefined or null reference.

Later instead:

 <script type= "Text/javascript" src= "transform.js" ></script> <script type= "Text/javascript" Language= "JavaScript" > //  var obj = document.b          Ody;  function   s22t () {Document.body.innerHTML  =s2t (documen             t.body.innerhtml);  //  Document.body.innerHTML   " function   t22s () {Document.body.innerHTML  =t2s (Document.body.innerHTML); }  </script> 

Then add the link in the appropriate location of the webpage: <a href= "javascript:s22t ()" > Traditional Chinese </a><a href= "javascript:t22s ()" > Simplified Chinese </a >

After saving the page, click "Traditional Chinese" link, the page will become traditional, click "Simplified Chinese" will be automatically converted to simplified form, convenient for different users to browse the choice.

Hint: This method not only applies to static website but also can be used in forum, message board and other dynamic website system.

Simple and complicated conversion of JS Web page

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.