Quick conversion of text language (Traditional Chinese and simplified Chinese) and JavaScript text based on javascript

Source: Internet
Author: User

Quick conversion of text language (Traditional Chinese and simplified Chinese) and JavaScript text based on javascript

Generally, commercial websites have a language requirement. In order to take care of Chinese people who use Chinese characters, they will provide a special option to switch to Chinese (or "Traditional Chinese "). The traditional method is to convert the text language through some controls or filters on the server. Here I will introduce a simple and feasible method, instead of using the front-end JavaScript on the server side, you can switch between the front-end Chinese characters.
For example, we place the switch button in the footer (you can also place it in the "navigation" or other more eye-catching positions ).

Since the page assumes that all settings use the Unicode Character Set, you generally do not need to consider the GB2312/BIG5 Character Set Problem, the great Unicode Character Set has covered the traditional characters (UTF-8 encoding ).

How can I call this function on a page? Very easy. first introduce the following Js (note that Function. prototype. delegate () is also dependent, which will be mentioned below ):

; (Function () {var Simplified Chinese = 'Ah, sorry, no cancer, no cancer, No. AI, No. Aile, by the case of the dark-shore amine, Ang, WA, WA, and AO ba Jie ba Bai banban move pull like board dress mix with half run the uncle Bang bang tied to the rod pound clam pound sideways slander bud bag peeling thin hail bao full bao burst cup Bei times ben benbenbenbenbenbenbenbenbenbenbenbenbenbenbenbenbenbenweitao pump burst into force nose compared with the computation pen Bi Bian bian bian will be changed to Bian Biao Yu table Yu Xiao Bin bing bo bo platinum foil bo cangcang Tibetan operations rough groove Cao toilet policy side volume test layer rub inserted cross cutting tea cha difference split Chai Yi mixed with Chan yi wrapped around shovel production explanation trembling chang sang Song Chao Yu Chao noisy car pull from Chen Shen chen yu lining said cheng qiu silk glared at the ugly smell. The first kitchen cupboard, the kitchen, and the chicks In addition to Chu's basic storage, Chu Yu's touchpoint, chuchuan, chuanchuan, chuanchuan, chuankechuan, chuankeba, sore, window building, chuangchuang, blowing, cooking, sleep, hammer down, Chunchun, alcohol, lips, Chunchun, dumbgez, magnetic female, Ci the word this thorn sent to the Cong shilui from the Cong together with the crude vinegar cluster to promote the destruction of the Cui reminder brittle essence of the quenching village Cun Jin beat up to answer big when I try to wear a bag on behalf of the loan, I want to catch it. When I try to use Dan dao Yu Dao De de di dian Yao Diao throttle fall hanging fishing tune dad dish butterfly stacked ding staring Ding ding set lost Dong understand Dong Shan frozen Holes doudou steep Doudou douque du Duan satin heap against the team of dunton dunting blunt shield yundun duo Yu yi Xi Er er Er send penalty raft cutting lack of valve law Yi fan fan FAN Fang anti-Fan Fei fen FENG Yu Feng Fu skin incubator Fu fu Fu Wu bind Xiao ga the change of calcium cover dry Gan rod citrus rod liver catch sense stalk dare Gan Gang gang bar high paste lambs cake pick draft report Ge put Ge gong mercury Gong Gou dog scale structure purchase enough Gu si Gu Gong guobiao guanguangguan Guan Guang Xi GUI Yu GUI Roll Stick pot Guo hao, Han hehehehehe and hehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehahaha hu HU Hua huan HUan Huang Wei Huang Yu lie gray Bo hui Yin wedding soul muddy mixed living group fire get or confused Huo's curse attack Ji that is, the upper-level crowded ridge Ji Jia K Jia jian Jiang Jian Jiao Jian jiaojiao handed in the cutting-and-cutting Jiaojiao sedan is more called Jianye jie Jing jing jiu according to the giant from the saw all sentence fear torch drama donate Juan tired Xi jie jin Jun ka Kai kai kai-kai-ke kong kukukun bundle, sleepy, including expanded, wide, Lala, wax, la, Lai, lan LAN Lang fishing la Lei Li Lei Li Lian curtain convergence face chain Lian Liang Xiao Xi Yu Liao He he Li Lin Adjacent Scales ling lu luanyi's eggs are being swept away. Lun luoluo bare luoluo Ma code and scold it? Bury it to buy Mai selling Mai jack manman man Mao mei simy Mei men stuffy men Meng Mn Meng mi ether Mi Mian Miao Scanning second Miao Xi Min Ming Wei mo Min mu Na na ne is milk Nai Nan capsule scratching the brain to make trouble? mud Ni you want to get tired of Yining Niang nig urine pinch Niang nisi tweezers Ni Niyou Niang Ning Twist the ox and twist the nets, the nnu, The Nuo, The Nuo, the Nuu, the Nuu, The Nuo, The Nuo pan hold the touch green batch peat the split peat pi que fart Article partial piece lie float the pass glance fight frequency poor products hire ping by bottle comment on pingpo po pu qi Qian the shortest horse is embedded with an apology gun. The upper part of the wall, the upper part, the lower part, and the lower part, the lower part poultry sleeping qinqing light hydrogen qingqing Cyanine qing Qiong Qiu Zheng qu Yu qu go circle quan aldehyde Quan que bonus bonus sansan umbrella sansong funeral Sao sweep sizing Samson Sensa Sha Drying Shan shen Sheng Shen Shi Shen shi Xi Shi shoushou Shou Shu playing the fall and drop handsome tie Shuang who water sleep shun Shun said Shuo si like feeding Si Song song sent song litigation to search for a ship, Su, Su he and her ta tutts, her TDE, And the ttan Tan tang if lying down Tang Tao Tang tao Zheng set Teng pain ladder ti Xiao shaving Tian fill in Tian Yi pick up tips jump tie Hall listen to Ting boat Tong bucket stab tube pain steal head transparent convex bald tutu tu Tutu TU Tuo dig Wa Po Wai Wan Wang wei Wen Jian q: Weng Yi, I am lying in the wowu, Wu xi xia Xian xiang Xiao harmonic writing mechanical unloading crab laxative diarrhea Xie Xiao salary core zinc xin Xin Xing Xiong Xiu XU Xu Xuan XU Xu xue Xun Jian Yan Xun Jian ya Yan yan Shi Yang yi yi Yin Ying Fei Yin Ying ying Yong youyouyouyou you Youyu youyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyouyou yu Bath yu Yuan Yue dizzy Yun pregnant zeching miscellaneous planting zai again in my temporarily likes dirty burial was Jade algae jujube early bath flea noise make soap stove dry responsibility choose ze thief how zeng Yi once presented the Zha Yi slag Zha Rolling Brake yunzha squeeze Zhan felt Zhan zhang zhangzhang zhangzhangzhangzhangzhangzhangzhangzhangzhangzhangzhangzhangzhang account Account zhanzhanzhanzhang zhazhao looking for Marsh Zhao cover Zhe zhe ge cane this Zhe Zhen Zhenzhen zhen Zheng Zhen Zhizhi zhizang Zhizhi zhongzhong final kinds of swelling zhongzhong Zhongzhou Zhouzhou Piao porridge axis elbow curse wrinkle Zhou day sudden Zhu zhuzhu cooking foresight zhu Zhuang makeup hitting Zhuang-shaped vertebral cone chasing actor pendant repair quasi catch Zhuo table you can enjoy the Zizi Zi drill your mouth and get drunk, the most sin Zun, zomoto Zuo, sitting seat '; var is a Chinese character = 'Ah ah, sorrow, cancer, AI, love, saddle, ammonia, and ammonia, by the case of the dark shore amine, Ang, WA, Yao, AO ba ba target to Harrow Chu ba Bai banban move pull-like cutting board version to mix with half a hole bang bang zookeeper baking was Benben benbenyi pump burst into the force nose compared to the cool Bibi blind yunqi yundun even when it is flat, it becomes difficult to distinguish between the two tables. bo Yi foil Bo yi neck Bo boo, Bo, Bao, Bao, Bu, Bu, bu Jie, Wei, Wei, Cai, Cai, Wei, Xiao, Yu, Yun slot, CaO, CaO, yi, cha, cha, Xiao, Chang, Chang changyun Changshou changzheng Chao Bo Cheechu to pull the brakes Chen Shen Yu Cheng cheng CHI yi Qiu Yu the first time the smell was found, the first time the smell was reached, the first time when the chuhuan district was wearing a boat, the chain was passed, the window, the bed was broken, the wind was broken, the grass was down, and the lips were refined. chungong taobaoque Ciz magnetic female ci CI this Thorn was used to promote the transformation from the tailu crude vinegar cluster to kill Cui qijing jicui Village learn how to deal with it, and then try again and answer your questions. Then, you can wear your replacement bag to catch up. when the eggs were being reached, the knives were being taken down, and then they were directed to the Dade's foot, and so on. di di Dian dingting Dingding Dongdong dongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongdongfud The dual end of the short segment of the zookeeper stack of the zookeeper of the United States, the United States er Zheng's suppression of ehan and his ears, the second generation, and the lack of cutting-edge methods, Fan Yi fang Fangfang anti-it-as-you-go anti-bot-like fufei Fei Yu Fei FENG boiling Fen Yu Feng Fengfeng when you encounter Fufu Fu fu He he I have written a draft for the High-paste lambing cake in the middle of the port, and told my goo to cut the GEG. stem Gong Gu guoguo hired guoguo, gritted, Guile, guoguo, guidao, guidao, and guidao huang Xiaoyu, Wang guoguo, wrapped in a shell, a child, and a child, he hahai, a disaster, and Han He ha hao High Consumption Hao hehao hehehehehehehehehehehehao hehao heoo he hate Heng Heng, Han, He, Huang, Hong, Huang, Hou, Hou hou Hou, Hou hou Hou, Hu HU, Hu, Huang, Yu, Hua, Yu, Hu when talking about translation, Huai Yu and Huai Yu are still suffering from translation, translation, and translation. hui Yao wedding soul co-occurrence of a fire, or he is confused zookeeper muscle Jiji Ji I remember that I was not afraid of being a prostitute. I was married to the famous Jia and the famous Jia. zookeeper mongoshake and zookeeper mongoshake in the suburbs of Zhejiang Province, Zhejiang Province, China jing JU Juan Wu Xi JU jie Yu jie Jin Jing Junjun Jun Kai kai ke kai ke Wei the basket is full of frames, and the eyes are full of helmets, and the hands of kubernetes kuaidi the langlang Lang R li lian Yi, he li Lin Ling long enough to keep the Lu Yu Lu the law rate is almost always the same. buried in the dark, the dead, the man, the blind man, the busy man, the Mao appearance Mei Mi. mi Yi Mian Miao scanning second Miao Min momo mo Mu na what about the inner tenderness of the Men's sachets, The Niang niyun, you have been a real cool, cool, crawling afraid of panpan Pan peng Ping taobao products hire ping po qi when Qian Qingqing qing Qiu qu Yu qu Quan jie Zheng que skirt group Ran the hustle and bustle of the soil allows the attackers to throw the Rong Rou Ru Ruyi Rugao if the weak swordsmanship sashes what sha Shan Shang the tongue of the house was shot and involved in the establishment of arsenic Shen was very careful when the birth of the animal was promoted to the province, the remaining amount was lost. when shishishishi was picked up, Shi Shiya, Shi room doctor shoushoushoushoushoushoushoushoushoushoushoushoushou shoushou Shou Shu Xian shushushu Shushu brush and drop tie shushushuang shushuang who water sleep sucking instant Shun said shuosi si like song Si, Song, and Song Yu are sent to search for the ship, and the Su Zhi Xiaoyi sour garlic. He was suffering from the collapse of his bone marrow, his ears, his eyes, his ears, his ears, his feet, his ears, his feet, his eyes, his ears, his ears tan tang Tao teng Yi, Xiao, Tang, Ting, Ting ting boat Tong bucket stab cylinder system pain shot through convex burst Tutu tu Tutu tuu leg yi fade swallow Tun hip Tuo Wa wa Wan Wang died innocent web to Wangwang forget Wei mosquito, Please, kiss, please, please xi the gap between the eyes and the eyes of the lower ears and the lower ears of the summer when the Xian xiang Xiao Xiao xing Hu Xiong Xiu Shu Xi XU Xu XU Xu Xuan xuxue Xue Xun Xu yan He yanyan yundun yanye Yizhi Yanyi Yizhi Yayi Yizhi yi Zheng Yi yi ying Yong Ying Yu yu. yu Yuan Yuan complained that the school was about to transfer the ticket, and the monthly ticket was rejected. zookeeper was buried with dead grains, algae, early bath, and noisy noise, soap, and dryness. How can this problem be solved? blow-up and pick up the house and narrow the village, Zhan zhangzhangzhang Zhang zhangzhang Zhan Zhuyu zhao looking for Marsh Zhao cover Zhe Zhen Zheng zookeeper Zheng Zhi zhizhizhizhizhizhizhizhizhizhizhizhizhizhizhizhizhizhizhizhongzhongzhongzhongzhizhongzhongzhongzhongzhouzhouzhouzhoupiao consortium elbow curse zhouzhouzhizhuzhu Strain the spider Zhu XiaoYu was made by bamboo. zombies chasing zombies Zizi Zi Zheng Zong when you go and play the role, you have to take the zuozu and drag the group to throw your mouth and get drunk, the most sin-Zun, And the zuozu Zuozuo to sit in the seat '; /*** whether the Chinese character is positive by default: true is positive, false is simplified. HTTP * Header read: Request. serverVariables ("http_accept_language") ** @ return {Boolean} */function getClientLanguage () {var s = navigator. userLanguage | navigator. language; switch (s. toLowerCase () {case 'zh-cn': return false; case 'zh-tw ': return true; default: return null ;}}/*** conversion object, use recursion to strip to text layer by layer * @ param {HTMLElement} obj from document. body, */function translate (el, coverntFn) {el = el. childNode S; var node; for (var I = 0, j = el. length; I <j; I ++) {node = el. item (I); // | (node ==$ $. big5.el) if ("| BR | HR | TEXTAREA | ". indexOf ("|" + node. tagName + "|")> 0) continue; if (node. title) {node. title = coverntFn (node. title);} else if (node. alt) {node. alt = coverntFn (node. alt);} else if (node. tagName = "INPUT" & node. value! = "" & Node. type! = "Text" & node. type! = "Hidden") {node. value = coverntFn (node. value);} else if (node. nodeType = 3) {node. data = coverntFn (node. data);} else {arguments. callee (node, coverntFn) ;}} function translateText (text, isBig5) {var str = [], _ char, charIndex, result; for (var I = 0, j = text. length; I <j; I ++) {_ char = text. charAt (I); charIndex = isBig5? Simplified Chinese. indexOf (_ char): Chinese text. indexOf (_ char); result = isBig5? Chinese character. charAt (charIndex): simplified Chinese character. charAt (charIndex); str. push (charIndex! =-1? Result: _ char);} return str. join ('');} var traditionalized = translateText. delegate (null, true), simplized = translateText. delegate (null, false); var cookieName = 'chinesetype '; // convert it to a window in Chinese (Traditional Chinese. toChinese = function (el) {el. addCls ('selected'); document. querySelector (". simpleChinese "). removeCls ('selected'); translate (document. body, traditionalized) Cookie. set (cookieName, true);} // convert to simplified Window. toSimpleChinese = function (el) {el. addCls ('selected'); document. querySelector (". chinese "). removeCls ('selected'); translate (document. body, simplized); Cookie. set (cookieName, false);} var Cookie = {set: function (name, val) {var exp = new Date (); exp. setDate (exp. getDate () + 600*1000); document. cookie = name + "=" + escape (val) + "; expires =" + exp. toGMTString () ;}, del: function (nam E) {document. cookie = name + "=; expires =" + (new Date (0 )). toGMTString () ;}, get: function (name) {var cookieArray = document. cookie. match (new RegExp ("(^ |)" + name + "= ([^;] *) (; | $)"); if (cookieArray! = Null) return unescape (cookieArray [2]); else return null ;}}; var value = Cookie. get (cookieName); if (value = null & getClientLanguage () | value = 'true') {// if the cookie is not checked, it is run for the first time. // The cookie retains the selected positive body and converts the original simplified word to the default positive body! Window. toChinese (document. querySelector (". Chinese");} else if (value = null &&! GetClientLanguage () | value = 'false') {// although it is run for the first time, it is simplified Chinese and does not need to be transferred. // It is already in simplified format and does not need to be converted. }})();

Then bind the button event. We simply use onclick to bind the global functions window. toChinese (el) and window. toSimpleChinese (el ). El is a button element.

// Convert the image to a window in Chinese (Traditional Chinese. toChinese = function (el) {el. addCls ('selected'); document. querySelector (". simpleChinese "). removeCls ('selected'); translate (document. body, traditionalized) Cookie. set (cookieName, true);} // converts it to a simplified Chinese window. toSimpleChinese = function (el) {el. addCls ('selected'); document. querySelector (". chinese "). removeCls ('selected'); translate (document. body, simplized); Cookie. set (cookieName, false );}

The two long string variables in js Code are simplified Chinese and Traditional Chinese. There is no magic in switching between them, but all the text can be matched one by one through these variables. Of course, this is only a commonly used correspondence between complexity and simplicity, and it is mechanical. Some special translations need to be associated with the context. This kind of advanced conversion is not discussed here.

First, let's look at the variable function translate and execute it to recursively traverse the entire DOM (it can be said that it is a stupid method)

/*** Convert the object and use recursion to strip it to the text layer by layer * @ param {HTMLElement} obj from document. body, */function translate (el, coverntFn) {el = el. childNodes; var node; for (var I = 0, j = el. length; I <j; I ++) {node = el. item (I); // | (node ==$ $. big5.el) if ("| BR | HR | TEXTAREA | ". indexOf ("|" + node. tagName + "|")> 0) continue; if (node. title) {node. title = coverntFn (node. title);} else if (node. alt) {node. alt = coverntFn (node. al T);} else if (node. tagName = "INPUT" & node. value! = "" & Node. type! = "Text" & node. type! = "Hidden") {node. value = coverntFn (node. value);} else if (node. nodeType = 3) {node. data = coverntFn (node. data);} else {arguments. callee (node, coverntFn );}}}

To convert DOM content, we may first think of el. innerHTML, but in fact it is not necessary, and it is not convenient to recursion. Let's look at it again. In fact, we only need to convert the text, and dom api can determine the text node (node. nodeType = 3), and then the readable and writable data attribute is set text (textNode. data. The same principle applies to other node attributes such as title, alt, and value. In addition, if ("| BR | HR | TEXTAREA | ". indexOf ("|" + node. tagName + "|")> 0) continue; is a method to exclude certain nodes. The idea is special and can be used for reference.

CoverntFn is a function parameter. Generate two new functions through the root function translateText (text, isBig5): var traditionalized = translateText. delegate (null, true), simplized = translateText. delegate (null, false );

Function translateText (text, isBig5) {var str = [], _ char, charIndex, result; for (var I = 0, j = text. length; I <j; I ++) {_ char = text. charAt (I); charIndex = isBig5? Simplified Chinese. indexOf (_ char): Chinese text. indexOf (_ char); result = isBig5? Chinese character. charAt (charIndex): simplified Chinese character. charAt (charIndex); str. push (charIndex! =-1? Result: _ char);} return str. join ('');} var traditionalized = translateText. delegate (null, true), simplized = translateText. delegate (null, false );

Function. prototype. delegate () method.

/*** Function delegate * @ return {Function} */Function. prototype. delegate = function () {var self = this, scope = this. scope, args = arguments, aLength = arguments. length, fnToken = 'function'; return function () {var bLength = arguments. length, Length = (aLength> bLength )? ALength: bLength; // mission one: for (var I = 0; I <Length; I ++) if (arguments [I]) args [I] = arguments [I]; // copy The args parameter. length = Length; // under the MS jscript, there is still a problem with arguments as a number, that is, length cannot be automatically updated. For example, left: // mission two: for (var I = 0, j = args. length; I <j; I ++) {var _ arg = args [I]; if (_ arg & typeof _ arg = fnToken & _ arg. late = true) args [I] = _ arg. apply (scope | this, args);} return self. apply (scope | this, args );};};

This is basically the case for simple conversions. It is worth mentioning that the browser actually identifies the variables of the language environment for us, mainly navigator. userLanguage | navigator. language. This variable can also be obtained on the server. The header is read: Request. ServerVariables ("http_accept_language ").

/*** Whether the Chinese character is positive by default: true is positive, false is simplified. HTTP * Header read: Request. serverVariables ("http_accept_language") ** @ return {Boolean} */function getClientLanguage () {var s = navigator. userLanguage | navigator. language; switch (s. toLowerCase () {case 'zh-cn': return false; case 'zh-tw ': return true; default: return null ;}}

Finally, we use cookies to save the language status.

The above is all the content of this article, hoping to help you learn.

Articles you may be interested in:
  • How to quickly switch between traditional Chinese and simplified Chinese using JavaScript

Related Article

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.