JavaScript/jQuery - Get text and translate it

只谈情不闲聊 提交于 2019-11-28 11:33:15

Use Google translation API. Easy to use. The following translates Spanish to English. To translate from and to other languages, simply change 'es' and 'en'

<div id="content"></div>

google.load("language", "1");

function initialize() {
    var content = document.getElementById('content');
    content.innerHTML = '<div id="text">Hola, me alegro mucho de verte.<\/div><div id="translation"/>';
    var text = document.getElementById("text").innerHTML;
    google.language.translate(text, 'es', 'en', function(result) {
        var translated = document.getElementById("translation");
        if (result.translation) {
            translated.innerHTML = result.translation;
        }
    });
}
google.setOnLoadCallback(initialize);

Check working example at http://jsfiddle.net/wJ2QP/1/

Use this JQuery plugin http://www.openxrest.com/translatejs

1 - Include the "trn" class to the text you want to translate:

<span class="trn">text to translate</span>

2 - Define a dictionary:

var dict = {
  "text to translate": {
    pt: "texto para traduzir"
  },
  "Download plugin": {
    pt: "Descarregar plugin",
    en: "Download plugin"
  }
}

3 - Translate the entire page body:

var translator = $('body').translate({lang: "en", t: dict}); //use English

4 - Change to another language:

translator.lang("pt"); //change to Portuguese

Use the Bing translator, since the free Google Translate API has been discontinued on December 1, 2011

Jhourlad Estrella

You can use Google Translate's Javascript API.

<p id="some">Hello</p>
<input id="trans" value="Translate" type="button">

<script>
   $('#trans').click(function() {
     google.language.translate($('#some').html(), 'en', 'fr', function(result) {
         $('#some').html(result.translation);
     });
   });
</script>

You will need to load the js library in your page's HEAD section in order to use the API.

On this PHP/JS solution you should use include PHP language files and set language on session/cookie not on $_GET. For the sake of simplicity I will do it on the

index.php file

<?php
$lang = $_GET['lang'];

if ($lang == 'fr'){
    $w = array(
        'Trouvé',
        ' non trouvé.',
        'Erreur. Veuillez réessayer.'
    );  
}else if($lang == 'en'){
    $w = array(
        'Found',
        ' not found.',
        'Error. Please try again.'
    );  
}else{
    $w = array(
        'Trouvé',
        ' non trouvé.',
        'Erreur. Veuillez réessayer.'
    );  
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
....................
<body>
....................
    <script type="text/javascript">
        /*  Translate JS
            Declare JS variables for translation in PHP file as below (Global vars outside $(document).ready). 
            Inside JS file call the variable as $.lang_mynamespace.var_name
        */
        $.lang_scan = { 
            found_js:"<?=$w[0];?>",
            not_found_js:"<?=$w[1];?>",
            error_js:"<?=$w[2];?>"
        };  
    </script>
</body>
</html>

JS file

$(function() {
    $("#scan_result").on('change', function(){

        //check number
        $.ajax({
            url: "check.php",
            dataType: "json",
            type: "post",
            data: {'scan_no': scan_value} ,
            success: function (response) {
                if (response.status == true){
                    alert("Scan no. " + response.scan_no + $.lang_scan.found_js);
                }else{
                    alert("Scan no. " + response.scan_no + $.lang_scan.not_found_js);                      
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
               //ajax error 
               alert($.lang_scan.error_js);            
            }
        }); 

    }); 
});

check.php return a json

{"scan_no": "123", "status": true/false}

Why not try this:

var body = $("body");
var html = body.html();
var nhtml = html.split(" ");
var dict = [];
for (var i = 0; i < nhtml.length; i++) {
    nhtml[i].replace(dict[index]);
}

It can replace anything.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!