如何使用javascript进行unescape并使用Google进行翻译?

时间:2014-05-20 13:55:11

标签: javascript html window google-translate

我有一些代码,当我在文本框中输入一些测试并单击“Tranlate”时,它将翻译为英语:

    <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/

现在,我想输入一些代码到 text1 :\ u83B7 \ u53D6 \ u9875 \ u9762我希望当我点击翻译它会自动 unescape() javascript “\ u83B7 \ u53D6 \ u9875 \ u9762”获取页面并自动翻译为英语,Google翻译并显示为 text1 。怎么做?

抱歉我的英文!

1 个答案:

答案 0 :(得分:0)

可能有一种更短的方法,但一种选择是使用JSON预定义类来处理所有转义。 encodeURI / decodeURI听起来就像最明显的方法,但它们都没有按照你想要的方向工作,即采用实际上称为“\ u83B7 \ u53D6 \ u9875 \ u9762”的字符串文字,包括文字反斜杠。你想要的是基本上重新评估输入字符串。

我能够这样做:

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

现在我的encodedChars获取页面。将其传递给您的翻译。