简体   繁体   English

如何使用javascript取消转义并使用Google翻译?

[英]How to unescape with javascript and translate with Google?

i have some code, when i input some test to text box and click Tranlate it will translate to English: 我有一些代码,当我在文本框中输入一些测试并单击“翻译”时,它将翻译为英语:

    <html> 
    <head> 
    <style type="text/css">
    input {font-size:12px; width:600px;}
            </style>    
    <title>Translate</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head> 
    <body> 
            <div class="translate"></p>
        <div class="translate_control" lang="en">   
        <input id="text1" class="translate"/>
         <script>
            function googleSectionalElementInit() {
            new google.translate.SectionalElement({
            sectionalNodeClassName: 'translate',
            controlNodeClassName: 'translate_control',
            background: '#f4fa58'
         }, 'google_sectional_element');
}
        </script>
        <script src="http://translate.google.com/translate_a/element.js?cb=googleSectionalElementInit&ug=section&hl=en"></script>   
    </body>
    </html>

http://jsfiddle.net/4CXGf/ http://jsfiddle.net/4CXGf/

Now, i want input some code to text1 as: \获\取\页\面 and i want when i click Translate it will auto unescape() with javascript "\获\取\页\面" to 获取页面 and auto translate to English with Google translate and show to text1 . 现在,我想将一些代码输入到text1中:\\ u83B7 \\ u53D6 \\ u9875 \\ u9762,当我单击“翻译”时,它将使用javascript “ \\ u83B7 \\ u53D6 \\ u9875 \\ u9762”自动unescape()获取页面并自动翻译使用Google翻译成英文并显示为text1 How to do it? 怎么做?

Sorry about my English! 对不起,我的英语!

There may be a shorter way to do this, but one option is to use the JSON predefined class to handle all the escaping. 可能有一种较短的方法,但是一种选择是使用JSON预定义类来处理所有转义。 encodeURI/decodeURI sound like the most obvious approach, but neither of them work in the direction you're trying for, which is to take a string literal that actually says "\获\取\页\面", including literal backslashes. encodeURI / decodeURI听起来是最明显的方法,但是它们都无法按照您想要的方向工作,即采用一个字符串文字,该文字实际上表示“ \\ u83B7 \\ u53D6 \\ u9875 \\ u9762”,包括文字反斜杠。 What you want is to essentially re-evaluate the input string. 您想要的实际上是重新评估输入字符串。

I was able to do this like so: 我能够这样做:

var escapedInput = document.querySelector("#text1").value;
var encodedChars = JSON.parse("\"" + escapedInput + "\"");

Now my encodedChars are 获取页面 . 现在我的encodedChars获取页面 Pass that to your translate. 将其传递给您的翻译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM